在Perl中,如何迭代数组的多个元素?

时间:2010-07-08 22:09:20

标签: perl

我有一个CSV文件,我使用split解析为N个项目数组,其中N3的倍数。

有没有办法可以做到这一点

foreach my ( $a, $b, $c ) ( @d ) {}

类似于Python?

5 个答案:

答案 0 :(得分:14)

我在CPAN上的模块List::Gen中解决了这个问题。

use List::Gen qw/by/;

for my $items (by 3 => @list) {

    # do something with @$items which will contain 3 element slices of @list

    # unlike natatime or other common solutions, the elements in @$items are
    # aliased to @list, just like in a normal foreach loop

}

您还可以导入mapn函数,List::Gen用于实现by

use List::Gen qw/mapn/;

mapn {

   # do something with the slices in @_

} 3 => @list;

答案 1 :(得分:12)

您可以使用List::MoreUtils::natatime。来自文档:

my @x = ('a' .. 'g');
my $it = natatime 3, @x;
while (my @vals = $it->()) {
    print "@vals\n";
}

natatime在XS中实现,因此您应该更喜欢它以提高效率。仅用于说明目的,以下是如何在Perl中实现三元素迭代器生成器的方法:

#!/usr/bin/perl

use strict; use warnings;

my @v = ('a' .. 'z' );

my $it = make_3it(\@v);

while ( my @tuple = $it->() ) {
    print "@tuple\n";
}

sub make_3it {
    my ($arr) = @_;
    {
        my $lower = 0;
        return sub {
            return unless $lower < @$arr;
            my $upper = $lower + 2;
            @$arr > $upper or $upper = $#$arr;
            my @ret = @$arr[$lower .. $upper];
            $lower = $upper + 1;
            return @ret;
        }
    }
}

答案 2 :(得分:4)

@z=(1,2,3,4,5,6,7,8,9,0);

for( @tuple=splice(@z,0,3); @tuple; @tuple=splice(@z,0,3) ) 
{ 
  print "$tuple[0] $tuple[1] $tuple[2]\n"; 
}

产生

1 2 3
4 5 6
7 8 9
0

答案 3 :(得分:4)

my @list = (qw(one two three four five six seven eight nine));

while (my ($m, $n, $o) = splice (@list,0,3)) {
  print "$m $n $o\n";
}

此输出:

one two three
four five six
seven eight nine

答案 4 :(得分:1)

不容易。通过将元素作为数组引用推送到数组上,你最好使@d成为一个三元素元组的数组:

foreach my $line (<>)
    push @d, [ split /,/, $line ];

(除非你真的应该使用CPAN中的一个CSV模块。