sachinmkulkarni has asked for the wisdom of the Perl Monks concerning the following question:

I have a list of hash, something like this. @ms, where $ms[0] = \%m ( a => 'x', b => 'y', c => 'z' );

I need to get an output list, @l, which consists of all the values corresponding to the key 'a' only if the value for the key 'b' is y.

For example: $ms[0] = \%m1 ( a => 'x1', b => 'y', c => 'z1' ); $ms[1] = \%m2 ( a => 'x2', b => 'y1', c => 'z2' ); $ms[2] = \%m3 ( a => 'x3', b => 'y', c => 'z3' ); $ms[3] = \%m4 ( a => 'x4', b => 'y2', c => 'z4' );
My output list @l = x1, x3 ; How do I achieve this using perl maps?

Replies are listed 'Best First'.
Re: Question related to map
by almut (Canon) on Jun 24, 2010 at 20:17 UTC
    my @ms = ( { a => 'x1', b => 'y', c => 'z1' }, { a => 'x2', b => 'y1', c => 'z2' }, { a => 'x3', b => 'y', c => 'z3' }, { a => 'x4', b => 'y2', c => 'z4' }, ); my @l = map $_->{a}, grep $_->{b} eq 'y', @ms;
Re: Question related to map
by Fletch (Bishop) on Jun 24, 2010 at 20:17 UTC

    a) You might try providing valid perl for your sample data (granted what you did provide is intelligible enough people probably will understand what you meant), and b) you want to use grep to select a list of matching items, then use map to extract the key from those.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Question related to map
by kennethk (Abbot) on Jun 24, 2010 at 20:18 UTC
    In general, using a foreach loop combined with a push will be clearer, however, you can do this fairly simply using map and the Conditional Operator (? :)

    #!/usr/bin/perl use strict; use warnings; my @ms = ( {a => 'x1', b => 'y', c => 'z1'}, {a => 'x2', b => 'y1', c => 'z2'}, {a => 'x3', b => 'y', c => 'z3'}, {a => 'x4', b => 'y2', c => 'z4'}, ); my @list = map {$_->{b} eq 'y' ? $_->{a} : () } @ms; print join "\n", @list;
Re: Question related to map
by planetscape (Chancellor) on Jun 25, 2010 at 01:13 UTC