2013-03-26 50 views
2

我正在運行以下簡單的Perl程序。在打印功能中使用未初始化的值

use warnings; 
use strict; 

my %a = (b => "B", c => "C"); 

print "Enter b or c: "; 

my $input = <STDIN>; 

print "The letter you just entered is: ", $input, "\n"; 

my $d = $a{$input}; 

print ($d); 

當我進入b時,我得到了以下輸出併發出警告。第47行是最後一條語句打印($ d);

Enter b or c: b 
The letter you just entered is: b 

Use of uninitialized value $d in print at C:/Users/lzhang/workspace/Perl5byexample/exer5_3.pl line 47, <STDIN> line 1. 

爲什麼我得到這個警告,我該如何解決?

+0

奇怪的想法來關閉這個問題... – 2014-06-06 08:05:55

回答

8

您的$input包含除bc以外的新行字符。修改它以修剪此字符:

my $input = <STDIN>;  # 1. $input is now "b\n" or "c\n"        
chomp $input;    # 2. Get rid of new line character 
          # $input is now "b" or "c" 

print "the letter you just entered is: ", $input, "\n"; 
+0

這是根本原因!謝謝! – Lyn 2013-03-26 22:21:01

3

這是因爲當您按回車鍵時,它會添加一個換行符。嘗試添加chomp以擺脫此。

chomp(my $input = <STDIN>); 

你得到警告,因爲值b\n不會映射到你的哈希值,從而$d未初始化。

+0

謝謝!如果只有我有更多的聲望來投票你的答案~~ – Lyn 2013-03-26 22:26:14

+0

@Lyn只要你明白哪裏出了問題,那麼一切都很好。乾杯。 – squiguy 2013-03-26 22:28:51