3

我正在运行以下简单的 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 行是最后一条语句 print ($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.

为什么我会收到此警告,我该如何解决?

4

2 回答 2

8

除了or之外,您$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";
于 2013-03-26T22:12:44.357 回答
3

这是因为当您按 Enter 时,它会添加一个换行符。尝试添加chomp以摆脱这种情况。

chomp(my $input = <STDIN>);

您会收到该警告,因为该值b\n未映射到哈希中的值,因此$d未初始化。

于 2013-03-26T22:12:48.493 回答