我想通过从数组 A 中获取第一个元素,从数组 B 中获取第一个元素,将两个长度相等的数组合并为一个数组;A 中的第二个元素,B 中的第二个元素等。以下程序说明了该算法:
# file zipper.pl
use strict;
use warnings;
use 5.010;
my @keys = qw/abel baker charlie dog easy fox/;
my @values = qw/a b c d e f/;
# ==> Is there a builtin function that is equivalent of zipper()? <==
#
my %hash = zipper( \@keys, \@values );
while ( my ( $k, $v ) = each %hash ) {
say "$k=$v";
}
# zipper(): Take two equal-length arrays and merge them (one from A, one from B,
# another from A, another from B, etc.) into a single array.
#
sub zipper {
my $k_ref = shift;
my $v_ref = shift;
die "Arrays must be equal length" if @$k_ref != @$v_ref;
my $i = 0;
return map { $k_ref->[ $i++ ], $_ } @$v_ref;
}
输出
$ ./zipper.pl
easy=e
dog=d
fox=f
charlie=c
baker=b
abel=a
我想知道我是否忽略了 Perl 中一个相当于 zipper() 的内置函数。它将位于程序的最内层循环,并且需要尽可能快地运行。如果没有内置或 CPAN 模块,任何人都可以改进我的实现吗?