Search code examples
arraysperlgrepdereference

Perl's grep does not work with dereferenced array


I wanted to find a perl equivalent to a python var in list idiom and stumbled on this.

The perl grep can do a grep { $_ eq $var } @list expression to match the element in list logic.

If I use a derefenced array like grep { $_ eq $var } @$list with $list defined as ['foo', 'bar'], I don't get the same outcome.

Is there a way to make grep work using dereferenced arrays?


Solution

  • That idiom should work fine; I think a code example where it's not working would be helpful. Just as a quickie toy example of this, though:

    #!/usr/bin/perl
    use strict;
    use warnings;
    
    use Test::More;
    
    sub find_var {
        my ($var,$array) = @_;
        print "Testing for $var in [" . join(',',@$array) . "]...\n";
        if ( grep $var eq $_, @$array ) {
            return "found it";
        } else {
            return "no match!\n";
        }
    }
    
    my @array = qw(apple pear cherry football);
    my $var = 'football';
    my $var2 = 'tomato';
    
    is(find_var($var, \@array), 'found it');
    is(find_var($var2, \@array), 'found it');
    done_testing();
    

    This results in the following output, which indicates that the first test for "football" in the array reference was successful, while the second test for "tomato" was not:

    Testing for football in [apple,pear,cherry,football]...
    ok 1
    Testing for tomato in [apple,pear,cherry,football]...
    not ok 2
    #   Failed test at array.pl line 22.
    #          got: 'no match!
    # '
    #     expected: 'found it'
    1..2
    # Looks like you failed 1 test of 2.