Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do the reverse of zip/mesh from List::MoreUtils?

Tags:

perl

I have two arrays:

@foo = (1, 2, 3, 4);
@bar = ('A', 'B', 'C', 'D');

If I zip them with mesh/zip from List::MoreUtils, I get this:

@zipped = (1, 'A', 2, 'B', 3, 'C', 4, 'D');

How can I do this operation backwards, i.e. starting from @zipped how can I get @foo and @bar?

like image 915
chris202 Avatar asked Feb 11 '15 23:02

chris202


1 Answers

List::Util::pairs.

use List::Util 'pairs';
my @zipped = ('1', 'A', '2', 'B', '3', 'C');
my ($foo, $bar) = pairs @zipped;

$foo and $bar will be references to arrays containing ('1'..'3') and ('A'..'C'), respectively.

Or if there are more than two arrays, use List::MoreUtils::part:

use List::MoreUtils 'part';
my @zipped = ('1', 'A', 'a', '2', 'B', 'b', '3', 'C', 'c');
my $number_of_arrays = 3;

my $i = 0;
my @arrayrefs = part { $i++ % $number_of_arrays } @zipped;
like image 109
ysth Avatar answered Oct 06 '22 03:10

ysth