in reply to Re: A classic use of prototypes: map2
in thread A classic use of prototypes: map2
Shouldn't $max_index be $min_index
Well, it's the minimum of the two indexes ... but it's the maximum value that the loop counter runs to. I was apparently thinking of the latter when I named the variable. Suggestions on a better name are welcome. (Maybe $shortest_array_len, which is closer in spirit to your suggestion as well as describing its role in the loop...)
There is no need to localize or subvert $a and $b. Just make the coderef act on $_[0] and $_[1] or their lexical copies.
My original code did exactly that... but I found myself using $a and $b anyway. And since perl exempts them from use strict checking, it would always take me a while to figure out what was going wrong.
For the record, the original that I spruced up a bit:
=item my @result = map2 BLOCK ARRAY, ARRAY Similar to c<map>, but operate on two lists at once. The values are passed in as two arguments. This has a particularly snazzy side effect; instead of projecting a list onto a series of hash keys the long way: my %hash; @hash{@hash_keys} = @values; You can just: my %hash = map2 { @_ } @hash_keys, @values; On the down side, I've burned myself more than once by using $a and $b with this function; perl has a special case to not warn about those. Grumble. =cut # create and test a "map2" function that behaves similar to the # built-in "map" function, but takes two lists instead of just one as # input. # # abigail wrote one that is much snazzier, but i can't find her web # page right now. # # similar to how "sort" takes its arguments, the block here should use # $a and $b for the two elements. the block is called in list # context, just as in the "real" map. # # originally written by afoiani a long time ago. sub map2 (&\@\@) { my ($code_ref, $a_ref, $b_ref) = @_; my $max_index = (@$a_ref < @$b_ref) ? @$a_ref : @$b_ref; my @rv; for (my $i = 0; $i < $max_index; ++$i) { push @rv, $code_ref->($a_ref->[$i], $b_ref->[$i]); } return @rv; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re^2: A classic use of prototypes: map2
by Zaxo (Archbishop) on May 02, 2004 at 07:10 UTC | |
by tye (Sage) on May 02, 2004 at 15:27 UTC |