2

私は現在、O'Reilly からIntermediate Perlを読んでいて、演習の 1 つを実行しようとしています。私は 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 に答える