2

我目前正在阅读O'Reilly 的Intermediate Perl并尝试做其中的一个练习。我对 Perl 中的引用不熟悉,所以我希望我不会误解某些东西并错误地编写此练习。

但是,我尝试调试此代码,但无法得出智能匹配行每次都失败的结论。据我了解@array ~~ $scalar,如果在@array.

下面是我的代码:

#!/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";
        }
    }
}
4

1 回答 1

4

如果您反转匹配,它将起作用:

$item ~~ @$items

或者

$item ~~ $items  # Smart-matching works with references too.

PS:习惯于添加use strict;到程序的开头。它会指出你的代码中的一些错误:)

于 2012-08-06T18:32:35.970 回答