如何使用Perl来遍历多维数组的内容并行 [英] How to Iterate the contents of multidimentional array in parallel using Perl

查看:395
本文介绍了如何使用Perl来遍历多维数组的内容并行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数组编号的数组。我试图从每个数组元素平行。一些身体可以帮助我。

  @洗牌=(
       [乔治,简,ELROY],
       [荷马史诗,玛吉,捷运],
       [弗雷德,巴尼]
);

我想这一点,但它依次遍历数组内

 我@fh;
#创建开放文件句柄的数组。
@fh = {图@ $ _} @shuffle;的foreach(@fh){
    我的$行= $ _;
    打印$行\\ n。}

和放出来是这样的:

 乔治

ELROY
本垒打
玛吉
巴特
弗雷德
巴尼

但我需要这样的输出:

 乔治
本垒打
弗雷德

玛吉
巴尼
ELROY
巴特


解决方案

你需要记住的事情是,当perl做一个它实际上是数组引用的数组。数组的数组

什么你与你的地图做有提领每个反过来,并通过这样做'压扁'阵列 - 把所有的元素在第一个数组引用那么第二等。

但是,这不是你想要什么来完成 - 你想采取的第一个的元素从每个,然后第二次,第三次再等。

但那个地图语句不会做的就是让你算你数组中元素的总数,它可以因此在使用时:

 我的@洗牌=(
       [乔治,简,ELROY],
       [荷马史诗,玛吉,捷运],
       [弗雷德,巴尼]
);同时,(地图{@ $ _} @shuffle){
    我的foreach $ sub_array(@shuffle){
       打印移位@ $ sub_array //'',\\ n;
    }
}

这可能不是测试,如果你完成了,虽然一个理想的方法 - 但它确实让你有内在的阵列不同长度

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

解决方案

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

这篇关于如何使用Perl来遍历多维数组的内容并行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆