首页 文章

Perl奇怪的缓冲输出行为

提问于
浏览
2

我最近一直在努力教自己Perl,并且一直在做一些基本的练习 . 在其中一个中,您有一个硬编码的姓氏哈希值 . 用户输入姓氏并输出名字 - 相对简单 . 代码如下:

#!/usr/bin/perl -w

use strict;
use warnings;

my %first_name = (
    Doe => 'John',
    Johnson => 'Bob',
    Pitt => 'Brad',
);

print "What is your last name?\n";
chomp (my $last_name = <STDIN>);
print "Your first name is $first_name{$last_name}.\n";

现在,发生了一些奇怪的事在我向程序输入内容之前不会显示 "What is your last name?\n" 行(并按Enter键),之后将打印以下内容:

What is your last name?
Your first name is .
Use of uninitialized value within %first_name in concatenation (.) or string at     test.pl line 14, <STDIN> line 1.

现在,我理解缓冲输出的概念以及所有这些,如果我在程序开头添加 $| = 1 ,它就可以工作了 . 但是,我的期望是,即使没有该行,即使 print 语句字符串可能不会立即打印,我的输入字符串仍将放在 $last_name 变量中,而不是 . 所以,我有两个问题:

  • 为什么会这样?它是操作系统的东西(我在Windows上运行)?

  • 为什么添加 \n 不会刷新输出(正如各种来源所说的那样)?

Note: 如果我通过简单打印 $last_name 变量来替换访问 %first_name 哈希的最后一行,那么即使输出仍然是"delayed",该变量的值也是正确的 .

Note #2 :或者,如果打印姓氏后的代码被替换为此,

if (exists $first_name{$last_name}){ 
   print "Your first name is $first_name{$last_name}.\n";
}

else{
    print "Last name is not in hash.\n";
}

然后 $last_name 确实从 <STDIN> 分配了正确的值 . 我不知道该怎么做 .

1 回答

  • 3

    您没有在程序中检查姓氏是否在哈希中,如果不是,那么您应该显示一些消息,例如“$ lastname not found” .

    顺便说一句,如果我输入正确的姓氏(存在于哈希中),你的程序就可以正常工作了 .

    所以你可以这样编辑你的程序:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my %first_name = (
        Doe => 'John',
        Johnson => 'Bob',
        Pitt => 'Brad',
    );
    
    print "What is your last name?\n";
    chomp (my $last_name = <STDIN>);
    
    # Check if the last_name exists in hash or not
    if (exists $first_name{$last_name}){ 
       print "Your first name is $first_name{$last_name}.\n";
    }
    
    # If it doesn't then show a custom message
    else{
        print "not found";
    }
    

    也许你是suffering from buffering .

相关问题