I recently \"needed\" a zip function in Perl 5 (while I was thinking about How do I calculate relative time?), i.e. a function that takes two lists and \"zips\" them togethe
This is totally not an elegant solution, nor is it the best solution by any stretch of the imagination. But it's fun!
package zip;
sub TIEARRAY {
my ($class, @self) = @_;
bless \@self, $class;
}
sub FETCH {
my ($self, $index) = @_;
$self->[$index % @$self][$index / @$self];
}
sub STORE {
my ($self, $index, $value) = @_;
$self->[$index % @$self][$index / @$self] = $value;
}
sub FETCHSIZE {
my ($self) = @_;
my $size = 0;
@$_ > $size and $size = @$_ for @$self;
$size * @$self;
}
sub CLEAR {
my ($self) = @_;
@$_ = () for @$self;
}
package main;
my @a = qw(a b c d e f g);
my @b = 1 .. 7;
tie my @c, zip => \@a, \@b;
print "@c\n"; # ==> a 1 b 2 c 3 d 4 e 5 f 6 g 7
How to handle STORESIZE/PUSH/POP/SHIFT/UNSHIFT/SPLICE is an exercise left to the reader.