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

查看:178
本文介绍了我如何比较在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");

所有的二,任意阵列(例如数组的元素可能对其他数据结构引用),可以使用的 数据::比较

对于数组的元素是标量,你可以用做对比 列表:: MoreUtils 成对BLOCK ARRAY1 ARRAY2 ,其中BLOCK是你比较子程序。你可以模仿配对(如果你没有列出:: 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;
        }
    }
}

P.S。我不知道,但列表::比较可能总是列表进行排序。我不知道这是否能做到两两比较。

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天全站免登陆