我想通过从数组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中的一个内建函数,这将相当于拉链()。它将在程序的最内层循环,并且需要尽可能快地运行。如果没有内置或CPAN模块,任何人都可以改进我的实现?
解决方法
其他人对网格/拉链方面的问题给出了很好的答案,但是如果您只是从一系列键和一个值创建哈希,您可以使用不赞赏的
hash slice。
#!/usr/bin/env perl
use strict;
use warnings;
my @keys = qw/abel baker charlie dog easy fox/;
my @values = qw/a b c d e f/;
my %hash;
@hash{@keys} = @values;
use Data::Dumper;
print Dumper \%hash;
附录
我想到为什么可以选择一种方法。我个人认为切片实现与zip一样可读,但其他可能不同意。如果你经常这样做,你可能会关心速度,在这种情况下,切片形式更快。
#!/usr/bin/env perl
use strict;
use warnings;
use List::MoreUtils qw/zip/;
use Benchmark qw/cmpthese/;
my @keys = qw/abel baker charlie dog easy fox/;
my @values = qw/a b c d e f/;
cmpthese( 100000,{
zip => sub {
my %hash = zip @keys,@values;
},slice => sub {
my %hash;
@hash{@keys} = @values;
},});
结果:
Rate zip slice zip 51282/s -- -34% slice 78125/s 52% --