2012-10-19 55 views
2

我最近一直在试图自学Perl并一直在做一些基本的练习。在其中之一,你有一个硬编码的姓氏到名字的散列。用户输入姓氏并输出名字 - 相对简单。代码如下: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"; 

现在,发生了一些奇怪的事情。该“什么是你的姓\ 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变量中,但事实并非如此。所以,我有两个问题:

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

注:如果我更换与$last_name变量的简单的印刷访问%first_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>分配正确的值。我不知道该怎么做。

+1

它在我的Mac上正常工作,所以我认为这是一个Windows问题。 – Barmar

+0

你在Windows上使用了什么perl风格? – ysth

+0

@ysth:ActivePerl – nickolayratchev

回答

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

+0

是的,我省略了检查,因为这个例子并不重要。但是,问题仍然存在:'$ last_name'变量未被赋予''的值。我不确定这只是一个Windows问题(更可能是我的代码中的一些细微之处?) - 我使用的是ActivePerl,如果这种奇怪和令人困惑的行为是由于Windows造成的,至少其中一个是3使用Perl for Windows的开发者会抱怨:) – nickolayratchev

+0

'$ | = 1'会解决这个问题,但我不明白为什么没有它就无法工作。 –

+0

顺便看看这个:http://perl.plover.com/FAQs/Buffering.html –