|
Posted by szr on March 21, 2008, 4:10 am
Please log in for more thread options benkasminbullock@gmail.com wrote:
>
>> So why not simply make grep context aware too? Seems grep would
>> benefit from this just as much, if not more, as map.
>
> I agree that if it's easy to make grep context aware, then they might
> as well. For example if "grep" is called in void context Perl could
> automatically replace the call to "grep" with one to "map".
>
> But as far as I know, "grep" wouldn't benefit from this. I think
> "grep" is exactly the same thing as "map" except for its return
> values. The difference in the return values is that "grep" returns a
> list of values where the evaluated expression or block is true,
> whereas "map" returns all the values. The side-effects of "grep" and
> "map" are identical. Thus calling "grep" in a void context has exactly
> the same effect as calling "map", and the FAQ entry is just saying if
> you are going to ignore the return value, there is a penalty to using
> "grep", so you should have used "map".
I get that, though I think there may be some cases where one might want
to use grep and it's filtering to compare the 'size' it returns to the
original size of the array.
For example:
my @a1 = ( [qw/A B C/], [qw/D E F/], [qw/G H I/] );
my @a2 = ( [qw/A B C/], [qw/D E F/], [qw/G H I/] );
my $match =
@a1 == grep { my $i = $_;
@ == grep {
$a1[$i][$_] eq $a2[$i][$_];
} (0..$#)
} (0..$#a1);
print $match;
I don't see why there should be a performance penalty in this example,
if it was avoided with map. Making grep context aware would be real nice
if you change the arrays to have 100_000 elements each.
--
szr
|