Search code examples
perlreferencesmartmatch

Why does smartmatch not work when dereferencing an arrayref on the left-hand side?


I am currently reading Intermediate Perl from O'Reilly and am attempting to to do one of the exercises. I am new to references in Perl, so I hope that I am not misunderstanding something and coding this exercise incorrectly.

However, I have tried to debug this code and I am not able to come to a conclusion as to how the line with the smart matching is failing every time. From what I understand @array ~~ $scalar should return true if the string-wise scalar value is found in the @array.

Below is my code:

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

Solution

  • If you reverse the match it will work:

    $item ~~ @$items
    

    or

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

    PS: get used to adding use strict; to the start of your program. It will point you to a few mistakes in your code :)