Perl 并行迭代 2 个数组的方法 [英] Perl way of iterating over 2 arrays in parallel
问题描述
我用过
Use List::MoreUtils qw(each_array);
my $it = each_array( @input_dump_arr, @created_dump_arr);
while ( my ($first, $second) = $it->()) {
}
这可以在默认的 perl 配置中工作吗?一个更广泛的问题是是否有编写可移植"perl 脚本的指南?我是 Perl 的新手,只是想弄清楚 cpan 是否真的类似于 boost 库对 C++ 的影响.
Would this work in a default perl configuration? A broader question is are there guidelines to write "portable" perl scripts? I'm new to Perl, just trying to figure out if cpan is actually analogous to how boost libraries are to c++.
推荐答案
您可能希望使用模块的 each_arrayref
函数的这种更简单的重写.each_array
是这个函数的多余包装器,它使用原型来获取对作为参数传递的数组的引用.
You may want to use this simpler rewrite of the module's each_arrayref
function. each_array
is a superfluous wrapper around this function that uses prototypes to take references to arrays passed as parameters.
它的功能与模块版本相同,只是它不检查接收到的参数,并且返回的迭代器不检查它是否没有参数或'index'
.
Its functionality is identical to the module version, except that it does no checking of the parameters it receives, and the iterator returned doesn't check that it has either no parameters or 'index'
.
use strict;
use warnings;
sub each_array {
my @copy = @_;
my $i;
my $max;
for (map scalar @$_, @copy) {
$max = $_ unless defined $max and $max > $_;
}
sub {
return $i if @_ and shift eq 'index';
my $new_i = defined $i ? $i + 1 : 0;
return if $new_i >= $max;
$i = $new_i;
return map $_->[$i], @copy;
}
}
my @array1 = qw/ A B C /;
my @array2 = qw/ D E F G /;
my $iter = each_array(\@array1, \@array2);
while (my @values = $iter->()) {
printf "%d: %s\n", $iter->('index'), join ', ', map $_ // 'undef', @values;
}
输出
0: A, D
1: B, E
2: C, F
3: undef, G
当然,您可以简单地从 List::MoreUtils
模块中获取 each_arrayref
的代码.它是独立的,将保证与您现有的代码兼容.
You could, of course, simply take the code for each_arrayref
from the List::MoreUtils
module. It is self-contained and will guarantee compatibility with your existing code.
这篇关于Perl 并行迭代 2 个数组的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!