gpt4 book ai didi

arrays - 在 Perl 中,是否有内置方法来比较两个数组是否相等?

转载 作者:行者123 更新时间:2023-12-03 01:13:48 50 4
gpt4 key购买 nike

我有两个字符串数组,我想比较它们是否相等:

my @array1 = ("part1", "part2", "part3", "part4");
my @array2 = ("part1", "PART2", "part3", "part4");

是否有像标量那样比较数组的内置方法?我尝试过:

if (@array1 == @array2) {...}

但它只是在标量上下文中评估每个数组,因此比较每个数组的长度。

我可以滚动自己的函数来执行此操作,但这似乎是一个低级操作,应该有一个内置的方法来执行此操作。有吗?

编辑:遗憾的是,我无法访问 5.10+ 或可选组件。

最佳答案

有新的 smart match operator :

#!/usr/bin/perl

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 :

Internally the comparator compares the two arrays by using join to turn both arrays into strings and comparing the strings using eq.

我想这是一个有效的方法,但只要我们使用字符串比较,我宁愿使用类似的方法:

#!/usr/bin/perl

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

如果您要比较的数组很大,那么将它们连接起来会比只是逐个比较每个元素需要做大量的工作并消耗大量的内存。

更新:当然,应该测试这样的陈述。简单的基准:

#!/usr/bin/perl

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_compiterator    246/s         --       -75%array_comp 1002/s       308%         --

On the other hand, the best case scenario is:

my @x = map { rand } 1 .. 1_000;
my @y = map { rand } 1 .. 1_000;
              Rate array_comp   iteratorarray_comp   919/s         --       -98%iterator   52600/s      5622%         --

iterator performance drops quite quickly, however:

my @x = 1 .. 20, map { rand } 1 .. 1_000;
my @y = 1 .. 20, map { rand } 1 .. 1_000;
              Rate   iterator array_compiterator   10014/s         --       -23%array_comp 13071/s        31%         --

我没有查看内存利用率。

关于arrays - 在 Perl 中,是否有内置方法来比较两个数组是否相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1609467/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com