in reply to A classic use of prototypes: map2

Shouldn't $max_index be $min_index and look like this?

my $min_index = @$a_ref < @$b_ref ? $#$a_ref : $#$b_ref;
There is no need to localize or subvert $a and $b. Just make the coderef act on $_[0] and $_[1] or their lexical copies.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: A classic use of prototypes: map2
by tkil (Monk) on May 02, 2004 at 07:04 UTC
    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:

      You get trouble with undefined quantities if you go beyond the minimum last index. Your updated code still uses @$arrayref instead of $#$arrayref as the last index of the referenced array.

      After Compline,
      Zaxo

        Since < is used, @$aref is correct. Using $#$aref would work if <= were used. I prefer the former. But for that case the variable shouldn't be called "last index" and in the current code (that appears to keep changing -- so I'm not claiming you were mistaken) it isn't ($rv_len).

        FYI, Algorithm::Loops includes several flavors of 'mapcar' which are like map2 but take N lists and pass the items into the code block via @_. The module documentation also discusses why I chose to use prototypes despite usually avoiding them.

        - tye