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";

现在,奇怪的事情发生了。直到我在程序中输入一些内容(然后按 Enter),才会显示“你的姓氏是什么?\n”行,然后打印以下内容:

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变量中,但事实并非如此。所以,我对此有两个问题:

  1. 为什么会这样?它是操作系统的东西(我在 Windows 上运行)吗?
  2. 为什么添加 a\n不会刷新输出(正如各种消息来源所说的那样)?

注意:如果我用变量%first_name的简单打印替换访问散列的最后一行$last_name,那么即使输出仍然“延迟”,变量也具有正确的值。

注意#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>。我不知道该怎么做。

4

1 回答 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";
}    

也许你正在遭受缓冲

于 2012-10-19T04:09:04.513 回答