Perl - 比较<stdin>和Hash Key&amp;值

时间:2018-05-07 06:17:08

标签: perl

我试图比较两个输入($ name,$ place)是否与哈希的相应键和值匹配。因此,如果$ name匹配一个键,$ place匹配该键的值,则打印“Correct”。不幸的是,我的代码不正确。有什么建议?谢谢!

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";
}

1 个答案:

答案 0 :(得分:-1)

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

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阅读时,您需要理智地检查输入,否则您会在结果中遇到这些问题(更不用说#34;正确!&#34;最后)意外输入:

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:请承担我的变量声明变更,它只是我的强迫症,与手头的问题无关。就像我说的那样可以做很多事。