note
BrowserUk
<blockquote><i></i></blockquote>
<p>Ah! I see what you mean. (I should have realised that, given you were advocating <code>mapcar()</code> (What the...?) :).
<p>The main reason for my avoiding lexicals in a utility sub of this type is that I want to retain the aliasing nature of <code>@_</code>. 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.)
<p>Perhaps these are more palatable?
<code>
#! 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
</code>
<p>Now, if anyone can tell me how to make <code>zipn</code> 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.
<p>Also, if anyone can see how to retain the alias status of the parameters to <code>zipn</code>, that would be really cool.
<div class="pmsig"><div class="pmsig-171588">
<hr />
<font size=1 >
<div>Examine what is said, not who speaks.</div>
"Efficiency is intelligent laziness." -David Dunham<br />
"Think for yourself!" - [Abigail-II|Abigail] <br />
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - [tachyon]<br />
</font>
</div></div>
406231
406368