in reply to map and grep syntax question

I'm as big a fan of grep and map as the next guy, but sometimes they just don't make sense. In this case, I think a plain for loop would be clearer:

my $parts = [ 'Part1', 'Part2','Part3' ]; my $newLoop; for (@$parts) { my $hash = { PARTNAME => $_ }; $hash->{SELECTED}++ if $_ eq $row->{title}; push @$newLoop, $hash; }

Or, if anything, just a single map call, but this demonstrates why I prefer the for loop:

my $parts = [ 'Part1', 'Part2','Part3' ]; my $newLoop = [ map {{ PARTNAME => $_, $_ eq $row->{title} ? (SELECTED => 1) : () }} @$parts ];

Update: Joost beat me to the punch on the single-map part, but I still prefer my first snippet.

Replies are listed 'Best First'.
Re^2: map and grep syntax question
by Joost (Canon) on Dec 10, 2004 at 22:06 UTC
Re^2: map and grep syntax question
by geektron (Curate) on Dec 10, 2004 at 22:46 UTC
    the straight map loop is the most concise, i think, plus i need to work more with some of the added list ops.

    i just want to extend my working knowledge of everything.

      the straight map loop is the most concise, i think

      The most concise solution is not always the best. Take a look at any Perl Golf contest for conclusive proof of this. :-) For example, here's another concise version:

      my $newLoop; push @{$newLoop},{PARTNAME=>$_,/$row->{title}/?(SELECTED=>1):()} for qw(Part1 Part2 Part3);

      But if I saw that in real code, I wouldn't be very happy.

      plus i need to work more with some of the added list ops. i just want to extend my working knowledge of everything.

      That's fine, but part of learning how to work with something is learning when not to use it. I can't say the map verion that Joost and I both came up with is the worst code I've seen, but it isn't particularly clear. So, learn how to use map, but also learn when to use something else.