我正在尝试编写我的第一个Perl程序,我在其中使用给定值更新哈希值:
sub changeMap {
my $done = 0;
my $daKey = 'a';
while($done == 0)
{
print "Please select the character you would like to remap: ";
my $selection1 = <STDIN>;
print "You selected $selection1\n";
print "Please select the character you would like to replace it with: ";
my $selection2 = <STDIN>;
my %tempHash = reverse %mapping;
my $daKey = $tempHash{$selection1};
print "$daKey";
$mapping{$daKey} = $selection2;
my $done1 = 0;
while($done1 == 0) {
print "Would you like to replace another? (y or n) ";
my $answer = <STDIN>;
if ($answer == 'y') {
$done1 = 1;
}
elsif ($answer == 'n') {
$done = 1;
$done1 = 1;
}
else {
print "Not a valid response.";
}
}
}
}
我收到此错误:
Use of uninitialized value $daKey in string at ./lastlab.pl line 117, <STDIN>
line 2 (#1)
(W uninitialized) An undefined value was used as if it were already
defined. It was interpreted as a "" or a 0, but maybe it was a mistake.
To suppress this warning assign a defined value to your variables.
To help you figure out what was undefined, perl will try to tell you the
name of the variable (if any) that was undefined. In some cases it cannot
do this, so it also tells you what operation you used the undefined value
in. Note, however, that perl optimizes your program and the operation
displayed in the warning may not necessarily appear literally in your
program. For example, "that $foo" is usually optimized into "that "
. $foo, and the warning will refer to the concatenation (.) operator,
even though there is no . in your program.
有什么建议吗?我无法确切地看到问题所在。我是Perl的新手,看起来我遇到了一些问题。
答案 0 :(得分:2)
您忘了告诉我们哪一行是第117行(生成警告的那一行),但是,从您收到的警告中,它应该是这一行:
print "$daKey";
警告告诉我们$daKey
未定义,那怎么会发生?
嗯,它从前一行得到它的值:
my $daKey = $tempHash{$selection1};
因此,如果$daKey
未定义,则$tempHash{$selection1}
必须未定义。 会如何发生?
在一般情况下,这可能以两种方式之一发生:
$selection1
存在于%tempHash
中,但具有未定义的值$selection1
在%tempHash
中不存在
醇>
但是,在这种特定情况下,%temphash
从reverse %mapping
获取其值。这个(到第一个近似值)交换了%mapping
的键和值,并且哈希值不能有未定义的键,因此%temphash
不能有未定义的值,所以#2 必须的情况:$selection1
标识%temphash
中不存在的密钥。
既然我们知道这一点,我们再次问自己调试的核心问题:&#34;这会怎么样?&#34;
好吧,$selection1
从行
my $selection1 = <STDIN>;
因此可能只是用户错误 - 用户可能输入的值不是%mapping
中的值(因此,不是%temphash
中的键并且您的代码不会尝试检测或处理此类错误。
但更可能的情况是,您需要chomp $selection1
从其末尾删除\n
(换行符)字符。从文件句柄(例如<STDIN>
)收到的输入几乎总是以换行符结束,而内部数据几乎永远不会,这会阻止它们彼此相等。