我目前正在阅读O'Reilly的Intermediate Perl并试图进行其中一项练习。我是Perl中的新手,所以我希望我不会误解某些内容并错误地编写这个练习。
但是,我试图调试此代码,我无法得出关于智能匹配的线路每次都失败的结论。根据我的理解@array ~~ $scalar
如果在@array
中找到字符串方式的标量值,则应该返回true。
以下是我的代码:
#!/usr/bin/perl -w
use 5.010;
my @rick = qw(shirt shotgun knife crossbow water);
my @shane = qw(ball jumprope thumbtacks crossbow water);
my @dale = qw(notebook shotgun pistol pocketprotector);
my %all = (
Rick => \@rick,
Shane => \@shane,
Dale => \@dale,
);
check_items_for_all(\%all);
sub check_items_for_all {
my $all = shift;
foreach $person (keys %$all) {
#print("$person\n");
$items = $all->{$person};
#print("@$items");
check_required_items($person, $items);
}
}
sub check_required_items {
my $who = shift; #persons name
my $items = shift; #reference to items array
my @required = qw(water crossbow);
print(
"Analyzing $who who has the following items: @$items. Item being compared is $item \n"
);
foreach $item (@required) {
unless (@$items ~~ $item) {
print "Item $item not found on $who!\n";
}
}
}
答案 0 :(得分:4)
如果您反转匹配,它将起作用:
$item ~~ @$items
或
$item ~~ $items # Smart-matching works with references too.
PS:习惯于在程序开头添加use strict;
。它会指出代码中的一些错误:)