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

ebdffaop  于 2022-11-24  发布在  Perl
关注(0)|答案(6)|浏览(117)

我有一个CSV文件,我使用split将其解析为N项的数组,其中N3的倍数。
有什么办法我可以做到这一点吗

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

类似于Python?

piwo6bdm

piwo6bdm1#

我在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;
xdnvmnnf

xdnvmnnf2#

您可以使用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;
        }
    }
}
ergxz8rk

ergxz8rk3#

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
w7t8yxp5

w7t8yxp54#

@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"; 
}

产生:

d7v8vwbk

d7v8vwbk5#

不容易。最好将@d设为三元素元组数组,方法是将元素作为数组引用推入数组:

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

(除了你真的应该使用CPAN的CSV模块之一。

dtcbnfnu

dtcbnfnu6#

从Perl v5.36开始,您可以完全做到这一点:

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

它是作为for_list实验特性实现的,因此您可以像使用use experimental qw(for_list)时那样忽略警告;
对于v5.36之前的版本,我们将依赖于上面提到的while/splice

相关问题