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;
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|