> > I'm cobbling up a bit of code that'll need to do something akin to 'map' on two
> > lists at the same time. ...
>
> Footnote: I realized, that while doing 'mapN' is interesting. what I'm actually
> in the midst of implementing is 'foreach' for multiple lists. The template I
> had in mind was something like:
> forall my ($lotsofvariables) (list of listrefs)
> and then it'd alias the vbls in the lotsofvariables [or en masse if there's an
> array, of course] to each parallel entry from the various lists.
>
> I wonder if there's a pretty/elegant way to do that...
Hi,
Pretty? Elegant? In my example, it depends whether you are examining
the point of use... or the implimentation. The principle is to covert:
@array1 = ["a", "b", "c"]
@array2 = ["1", "2", "3"]
into
@result = [ ["a", "1"],
["b", "2"],
["c", "3"] ];
and then iterate over that. Obviously, I called the function magic()
because it's going to seem rather complex and UGLY. Call it pre-mature
optimisation for speed, if you like. Code quality is about 0.1% and
does not reflect normal code quality, guess I wanted more to see if you
liked the approach. Do NOT use *as is*, you definately want to check
you get array-refs on all elements (skipped) since it's VERY easy to
do:
magic @array1, @array2;
and not get what you expected.
My license for this is simple: fix/improve, copy and paste. Oh, and
I don't want my name in your otherwise clean code :)
__PERL CODE__
#!/usr/bin/perl -w
use strict;
use Carp;
# Basic test... iterates over and prints results
my @result = magic(["1", "2", "3"], ["a", "b", "c"], ["x", "y", "z"]);
foreach (@result) {
my ($first, $second, $third) = @{$_};
# Do something with values
print "$first : $second : $third\n";
}
# The UGLY stuff
sub magic {
my @array = @_;
# Check we have only array references
# ... exercise for reader... laziness for me.
# Find length of first array, then check consistency
my $length = $#{$array[0]};
for (@_) {
if ($length != scalar $#{$_}) {
croak "Array lengths don't match";
}
}
# Combine everything, using an eval for speed
my @result;
my $code;
for (0..$#_) {
$code .= "my \@array_$_ = \@{\$array[$_]};\n";
}
$code .= 'for (0..$length) {'."\n".' push @result, [';
for (0..$#_) {
$code .= "\$array_${_}[\$_]";
$code .= ", " unless $#_ == $_;
}
$code .= "];\n}";
eval $code;
return @result;
}
__END__
Jonathan Paton <--- evil programmer
sub point {
(list != array) and see("Programming Perl, pages 72-76.");
}
=====
s''! v+v+v+v+ J r e P h+h+h+h+ !s`\x21`~`g,s`^ . | ~.*``mg,$v=q.
P ! v-v-v-v- u l r e r h-h-h- !12.,@.=m`.`g;do{$.=$2.$1,$.=~s`h
E ! v+v+v+ s k e h+h+ !`2`x,$.=~s`v`31`,print$.[$v+=$.]
R ! v-v- t H a c h h- !}while/([hv])([+-])/g;print"\xA"
L ! A n o t !';$..=$1while/([^!]*)$/mg;eval$.
__________________________________________________
Do You Yahoo!?
Everything you'll ever need on one web page
from News and Sport to Email and Music Charts
http://uk.my.yahoo.com