Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a reference to the list returned by Perl's grep?

Tags:

perl

I would like to use the grep function to filter a list of values and store a reference to the filtered list into a hash. What I am after is something like:

my $allValues = [
    'a',
    'unwanted value',
    'b',
    'c',
];

$stuff = {
    'values' => grep { $_ ne 'unwanted value' } @$allValues
};

Only, when I try that, the %$stuff hash is:

$VAR1 = {
          'b' => 'c',
          'values' => 'a'
        };

Is there a way to fix the anonymous hash-creating code so that I instead get:

$VAR1 = {
          'values' => [
                        'a',
                        'b',
                        'c'
                      ]
        };

But not by creating a local variable or calling a subroutine (in other words, all in-line)?

like image 801
Daniel Trebbien Avatar asked Nov 05 '12 17:11

Daniel Trebbien


1 Answers

try with:

$stuff = {
    'values' => [ grep { $_ ne 'unwanted value' } @$allValues ]
};
like image 155
Tudor Constantin Avatar answered Oct 05 '22 17:10

Tudor Constantin