[Purdue-pm] Can do better with map somehow?

Mark Senn mark at ecn.purdue.edu
Sun Nov 28 12:36:57 PST 2010


Dave Jacoby <jacoby at purdue.edu> wrote:
    My new solution:

    my $first = {
        'a' => { 'foo' => 1, 'bar' => 'Cheers', },
        'b' => { 'foo' => 3, 'bar' => 'Crow', },
        'c' => { 'foo' => 1, 'bar' => 'Neon Cactus', } } ;
    my $second ;
    %$second =
        map { $_, $first->{ $_ } }
        grep { $first->{ $_ }->{ foo } == 1 } # <-- WOW!
        keys %$first ;
    say Dumper $second ;

I think (but don't know for sure) Perl 5 will do the grep and
save all those results and then do the map.  For this small
example it probably won't matter much but if %$first was very
large the above may run out of memory.

I prefer this:

my $third;
map  { ($first->{$_}->{foo} == 1)  and  $third->{$_} = $first->{$_} }
    keys %$first;
say Dumper $third;

-mark


More information about the Purdue-pm mailing list