rpg
rpg

Reputation: 1652

Hash assignment with List::Util

Here is the small code

use List::Util qw(first);

my $x = {FOO => undef};
my @array = (1,2,3,4,5,6,7,8,9);

$x->{FOO} =
    {
        'INFO' => first { $_ eq 1 } @array,
        'TI' => first { $_ eq 2 } @array,
    };

It's not creating the nested hash - the anonymous hashref FOO has only one keypair. Here is the o/p

$VAR1 = {
          'FOO' => {
                     'INFO' => 1
                   }
        };

I am unable to figureout why is this happening? please help.

Upvotes: 1

Views: 128

Answers (1)

Eugene Yarmash
Eugene Yarmash

Reputation: 149806

The first function has the prototype of &@, which means that it takes a block and a list as arguments. Everything after the block is used as the list. Therefore your code is equivalent to:

$x->{FOO} = {    
    'INFO' => first { $_ eq 1 } (@array, 'TI' => first { $_ eq 2 } @array),
};

You can either put the whole first expression in parens, or use an anonymous sub:

$x->{FOO} = { 
    'INFO' => first(sub { $_ eq 1 }, @array),
    'TI'   => first(sub { $_ eq 2 }, @array),
}; 

Upvotes: 3

Related Questions