如何比较Perl中的数组?

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

内容简介:翻译自: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


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

查看所有标签

猜你喜欢:

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

Learning Python, 5th Edition

Learning Python, 5th Edition

Mark Lutz / O'Reilly Media / 2013-7-6 / USD 64.99

If you want to write efficient, high-quality code that's easily integrated with other languages and tools, this hands-on book will help you be productive with Python quickly. Learning Python, Fifth Ed......一起来看看 《Learning Python, 5th Edition》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具