如何在 Perl 中比较数组? [英] How can I compare arrays in Perl?

查看:60
本文介绍了如何在 Perl 中比较数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two arrays, @a and @b. I want to do a compare among the elements of the two arrays.

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

如果有任何元素匹配,则设置一个标志.有什么简单的方法可以做到这一点吗?

If any element matches then set a flag. Is there any simple way to do this?

推荐答案

首先,你的 2 个数组需要正确写入.

First of all, your 2 arrays need to be written correctly.

@a = ("abc","def","efg","ghy","klm","ghn");
@b = ("def","efg","ghy","klm","ghn","klm");

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

Second of all, for arbitrary arrays (e.g. arrays whose elements may be references to other data structures) you can use Data::Compare.

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

For arrays whose elements are scalar, you can do comparison using List::MoreUtils pairwise BLOCK ARRAY1 ARRAY2, where BLOCK is your comparison subroutine. You can emulate pairwise (if you don't have List::MoreUtils access) via:

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 可能总是对列表进行排序.我不确定它是否可以进行成对比较.

P.S. I am not sure but List::Compare may always sort the lists. I'm not sure if it can do pairwise comparisons.

这篇关于如何在 Perl 中比较数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆