Ah! I see what you mean. (I should have realised that, given you were advocating mapcar() (What the...?) :).
The main reason for my avoiding lexicals in a utility sub of this type is that I want to retain the aliasing nature of @_. If you look closely at the output from the second and third print statements, you'll see that they have side-effects. (Which will probably be considered as undesirable, but again, it is sometimes useful.)
Perhaps these are more palatable?
#! perl -slw
use strict;
use List::Util qw[ min ];
local $, = ' | ';
use constant {
CODEBLOCK => 0,
ARRAY_ONE => 1,
ARRAY_TWO => 2,
};
sub zip (&\@\@) {
map {
$_[CODEBLOCK]->(
$_[ARRAY_ONE][ $_ ],
$_[ARRAY_TWO][ $_ ]
)
} 0 .. (
@{ $_[ARRAY_ONE]} < @{ $_[ARRAY_TWO] }
? $#{ $_[ARRAY_ONE] }
: $#{ $_[ARRAY_TWO] }
);
}
my @x = 'a' .. 'z';
my @n = 1 .. 10;
print zip{ "@_" } @x, @n;
print zip{ $_[ 0 ] .= $_[ 1 ] } @x, @n;
print zip{ $_[ 0 ] .= $_[ 1 ] } @x, @n;
sub zipn (&\@\@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@) {
map {
my $i = $_;
$_[CODEBLOCK]->( map{ $_[ $_ ][ $i ] } 1 .. $#_ )
} 0 .. min map{ $#{ $_ } } @_[ 1 .. $#_ ];
}
my @a = split'','ARC';
my @b = 1 .. 3;
my @c = split'','ADP';
my @d = ( 1, 2, 0 );
print "\n---\n";
print for zipn{ join '', @_ } @a, @b, @c, @d;
__END__
[17:21:15.53] P:\test>406231
a 1 | b 2 | c 3 | d 4 | e 5 | f 6 | g 7 | h 8 | i 9 | j 10
a1 | b2 | c3 | d4 | e5 | f6 | g7 | h8 | i9 | j10
a11 | b22 | c33 | d44 | e55 | f66 | g77 | h88 | i99 | j1010
---
A1A1
R2D2
C3P0
Now, if anyone can tell me how to make zipn truely generic in the number of arrays it can deal with I'd be very interested. 20 is probably more than enough for any purpose I am likely to encounter, but I hate arbitrary limits.
Also, if anyone can see how to retain the alias status of the parameters to zipn, that would be really cool.
Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
-
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.