在打印功能中使用未初始化的值

Lyn*_*Lyn 3 perl

我正在运行以下简单的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);
Run Code Online (Sandbox Code Playgroud)

当我输入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.
Run Code Online (Sandbox Code Playgroud)

为什么我会收到此警告以及如何解决?

kam*_*uel 8

$input包含除了b或之外的新行字符c.修改它以修剪此charcter:

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";
Run Code Online (Sandbox Code Playgroud)