Perl - <STDIN> 与哈希键和值比较



我正在尝试比较两个输入($name、$place(是否与哈希的相应键和值匹配。因此,如果$name匹配某个键,并且$place与该键的值匹配,则会打印"正确"。不幸的是,我的代码不正确。有什么建议吗?谢谢!

use 5.010;
use strict;
use warnings;
my ($name, $place, %hash, %hash2);       
%hash = (
Dominic => 'Melbourne',
Stella => 'Beijing',
Alex => 'Oakland',
);
%hash2 = reverse %hash;
print "Enter name: ";
$name = <STDIN>;
print "Enter place: ";
$place = <STDIN>;

chomp ($name, $place);

if ($name eq $hash{$name} && $place eq $hash2{$place}) {
print "Correct!n";
} else {
print "NO!n";
}

虽然可以做很多事情来纠正这一点(与问题无关(,但这是必要的最小解决方案:

use 5.010;
use strict;
use warnings;
my %hash = (
Dominic => 'Melbourne',
Stella => 'Beijing',
Alex => 'Oakland',
);
print "Enter name: ";
my $name = <STDIN>;
print "Enter place: ";
my $place = <STDIN>;
if ($name and $place) {
chomp ($name, $place);
if (exists($hash{$name}) and ($place eq $hash{$name})) {
print "Correct!n";
} else {
print "NO!n";
}
} else {
print "ERROR: Both name and place required to make this work!";
}

当您从 STDIN 阅读时,您需要理智地检查输入,否则您会在意外输入的结果中遇到这些问题(更不用说最后的"正确!"(:

Enter name:
Enter place:
Use of uninitialized value $name in chomp at original.pl line 19.
Use of uninitialized value $place in chomp at original.pl line 19.
Use of uninitialized value $name in hash element at original.pl line 22.
Use of uninitialized value $name in string eq at original.pl line 22.
Use of uninitialized value in string eq at original.pl line 22.
Use of uninitialized value $place in hash element at original.pl line 22.
Use of uninitialized value $place in string eq at original.pl line 22.
Use of uninitialized value in string eq at original.pl line 22.
Correct!

而不是应该使用错误检查代码生成的:

Enter name:
Enter place:
ERROR: Both name and place required to make this work!

PS:请耐心等待我的变量声明更改,这只是我的强迫症,与手头的问题无关。就像我说的,可以做很多事情。

最新更新