Is there an elegant zip to interleave two lists in Perl 5?

后端 未结 7 793
一向
一向 2020-12-02 15:45

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

7条回答
  •  一个人的身影
    2020-12-02 16:27

    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.

提交回复
热议问题