如何比较Perl中的数组?

栏目: Perl · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/2591747/how-can-i-compare-arrays-in-perl

我有两个数组,@ a和@b.我想在两个数组的元素之间进行比较.

my @a = qw"abc def efg ghy klm ghn";
my @b = qw"def ghy jgk lom com klm";

如果任何元素匹配,则设置标志.有没有简单的方法来做到这一点?

首先,您的2个数组需要正确编写.
@a = ("abc","def","efg","ghy","klm","ghn");
@b = ("def","efg","ghy","klm","ghn","klm");

其次,对于任意数组(例如,其元素可能引用其他数据结构的数组),您可以使用 Data::Compare .

对于元素为标量的数组,可以使用 List::MoreUtils 成对BLOCK ARRAY1 ARRAY2进行比较,其中BLOCK是您的比较子例程.您可以通过以下方式模拟成对(如果您没有List :: MoreUtils访问权限):

if (@a != @b) {
    $equals = 0;
} else {
    $equals = 1;
    foreach (my $i = 0; $i < @a; $i++) {
        # Ideally, check for undef/value comparison here as well 
        if ($a[$i] != $b[$i]) { # use "ne" if elements are strings, not numbers
                                # Or you can use generic sub comparing 2 values
            $equals = 0;
            last;
        }
    }
}

附:我不确定,但 List::Compare 可能总是对列表进行排序.我不确定它是否可以进行成对比较.

翻译自:https://stackoverflow.com/questions/2591747/how-can-i-compare-arrays-in-perl


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Types and Programming Languages

Types and Programming Languages

Benjamin C. Pierce / The MIT Press / 2002-2-1 / USD 95.00

A type system is a syntactic method for automatically checking the absence of certain erroneous behaviors by classifying program phrases according to the kinds of values they compute. The study of typ......一起来看看 《Types and Programming Languages》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试