现在有了新的智能匹配运算符:
use 5.010;
use strict;
use warnings;
my @x = (1, 2, 3);
my @y = qw(1 2 3);
say "[@x] and [@y] match" if @x ~~ @y;
关于Array::Compare:
在内部,比较器使用join将两个数组转换为字符串,并使用eq
比较字符串。
我猜这是一种有效的方法,但只要我们使用字符串比较,我更愿意使用类似于以下的内容:
use strict;
use warnings;
use List::AllUtils qw( each_arrayref );
my @x = qw(1 2 3);
my @y = (1, 2, 3);
print "[@x] and [@y] match\n" if elementwise_eq( \(@x, @y) );
sub elementwise_eq {
my ($xref, $yref) = @_;
return unless @$xref == @$yref;
my $it = each_arrayref($xref, $yref);
while ( my ($x, $y) = $it->() ) {
return unless $x eq $y;
}
return 1;
}
如果你要比较的数组很大,拼接它们会比逐个比较每个元素要消耗更多的内存并且需要进行大量的工作。
更新:当然,应该测试这样的说法。简单的基准测试:
use strict;
use warnings;
use Array::Compare;
use Benchmark qw( cmpthese );
use List::AllUtils qw( each_arrayref );
my @x = 1 .. 1_000;
my @y = map { "$_" } 1 .. 1_000;
my $comp = Array::Compare->new;
cmpthese -5, {
iterator => sub { my $r = elementwise_eq(\(@x, @y)) },
array_comp => sub { my $r = $comp->compare(\(@x, @y)) },
};
这是最坏的情况,elementwise_eq
需要逐一比较两个数组中的每个元素1,000次,并且结果如下:
Rate iterator array_comp
iterator 246/s -- -75%
array_comp 1002/s 308% --
另一方面,最好的情况是:
my @x = map { rand } 1 .. 1_000;
my @y = map { rand } 1 .. 1_000;
率 array_comp 迭代器
array_comp 919/s -- -98%
iterator 52600/s 5622% --
iterator
的性能下降相当快:
my @x = 1 .. 20, map { rand } 1 .. 1_000;
my @y = 1 .. 20, map { rand } 1 .. 1_000;
比率 迭代器 数组推导
迭代器 10014/s -- -23%
数组推导 13071/s 31% --
我没有考虑内存利用。
Array::Compare
。 - Sinan Ünürmy $i;for my $e (@$xref) {return unless $e eq $yref->[$i++];}
在 v5.14.2 中速度要快得多。 - Hynek -Pichi- Vychodilmatch::simple
。 - G. Cito