What I\'m looking for is something like:
@list = qw(1 2 3 4 5 6);
foreach (@list) {
#perl magic goes here
print \"i: $i, j:$j\\n\";
}
I came up with this code to solve a similar requirement:
sub map_pairs(&\@) {
my $op = shift;
use vars '@array';
local *array = shift; # make alias of calling array
return () unless @array;
# Get package global $a, $b for the calling scope
my ($caller_a, $caller_b) = do {
my $pkg = caller();
no strict 'refs';
\*{$pkg.'::a'}, \*{$pkg.'::b'};
};
# Get index counter size.
my $limit = $#array/2;
# Localize caller's $a and $b
local(*$caller_a, *$caller_b);
# This map is also the return value
map {
# assign to $a, $b as refs to caller's array elements
(*$caller_a, *$caller_b) = \($array[$_], $array[$_+1]);
$op->(); # perform the transformation
}
map { 2 * $_ } 0..$limit; # get indexes to operate upon.
}
You use it like so:
@foo = qw( a 1 b 2 c 3 );
my @bar = map_pairs { "$a is $b" } @foo;
to get:
@bar = ( 'a is 1', 'b is 2', 'c is 3' );
I've been meaning to submit to the maintainer of List::MoreUtils, but I don't have an XS version to offer.