Reputation: 269
I have an array containing number of array. I am trying to get the element from each array parallely. Can some body please help me.
@shuffle= (
[ "george", "jane", "elroy" ],
[ "homer", "marge", "bart" ],
[ "fred", "barney" ]
);
I tried this, but it iterating the inner arrays sequentially.
my @fh;
#create an array of open filehandles.
@fh = map { @$_ } @shuffle;
foreach (@fh){
my $line = $_;
print $line."\n";
}
And out put is like this :
george
jane
elroy
homer
marge
bart
fred
barney
But I need the output like this :
george
homer
fred
jane
marge
barney
elroy
bart
Upvotes: 1
Views: 132
Reputation: 126772
You should use the each_arrayref
function from the List::MoreUtils
module.
The code would look like this:
use strict;
use warnings 'all';
use List::MoreUtils qw/ each_arrayref /;
use Data::Dump;
my @shuffle = (
[ qw/ george jane elroy / ],
[ qw/ homer marge bart / ] ,
[ qw/ fred barney / ],
);
my $iter = each_arrayref @shuffle;
while ( my @set = $iter->() ) {
dd \@set;
}
["george", "homer", "fred"]
["jane", "marge", "barney"]
["elroy", "bart", undef]
Upvotes: 3
Reputation: 53508
The thing you need to bear in mind is when perl does an 'array of arrays' it's actually an array of array references.
What you're doing with your map
there is dereferencing each in turn, and by doing so 'flattening' your array - taking all the elements in the first array reference, then the second and so on.
But that's not what you're trying to accomplish - you're trying to take the first element from each, then second, then third etc.
But what that map statement does do is allow you to count the total number of elements in your array, which can be used thus:
my @shuffle= (
[ "george", "jane", "elroy" ],
[ "homer", "marge", "bart" ],
[ "fred", "barney" ]
);
while ( map { @$_ } @shuffle ) {
foreach my $sub_array ( @shuffle ) {
print shift @$sub_array // '',"\n";
}
}
that's probably not an ideal way to test if you're finished though - but it does allow you to have varying lengths of inner arrays
Upvotes: 4
Reputation: 5921
Try this
my @shuffle= (
[ "george", "jane", "elroy" ],
[ "homer", "marge", "bart" ],
[ "fred", "barney" ]
);
for my $i(0..$#shuffle)
{
for my $j(0..$#shuffle)
{
print "$shuffle[$j][$i]\n";
}
}
Upvotes: -1