我如何比较在Perl阵列的不同元素呢? [英] How can I compare different elements of array in Perl?

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

问题描述

我是新来这个领域。所以恳请宽容我。我有两个数组:

I am new to this field. So kindly go easy on me. I have two arrays:

@array1 = ("ABC321", "CDB672", "PLE89",....);

@array2 = ("PLE89", "ABC678", "LMD789",...);

我想比较这两种不同的数组的元素。但是,我想只匹配字母字母。因此,举例来说,如果阵列相比, $阵列[2] 元素(PLE)应与 $数组2 [0] (PLE),同样 $数组1 [0] (ABC)应与 $阵列[1] ( ABC)。我能做到这一点一下午时间,但不能两者阵列中的所有元素在同一时间比较(即循环数组)。

I want to compare elements of these two different arrays. But, I want to only match letters with letters. So for instance, if arrays are compared, $array[2] element (PLE) should match with $array2[0] (PLE) and similarly $array1[0] (ABC) should match with $array[1] (ABC). I am able to do it one at time but not able to compare all elements of both array at the same time (that is looping the arrays).

    my ($value1)= ($array[2]=~ /([A-Z]+)[0-9]+/);
    print "Value1: $value1 \n";
    my ($value2)= ($array[0]=~ /([A-Z]+)[0-9]+/);
    print "Value2 : $value2 \n";
    if ($value1 eq $value2){
            print " length \n";
    }

如何做我设置了两个数组循环在同一时间有什么建议?

Any suggestions on how to do I set up loop for both arrays at the same time?

推荐答案

您可以使用哈希作为查找设备,并得到一个 O(M + N)解决方案(其中, M 是ARRAY1的长度和 N 是数组2的长度)。

You can use a hash as a lookup device and get an O(m+n) solution (where m is the length of array1 and n is the length of array2).

#!/usr/bin/perl

use strict;
use warnings;

my @array1 = qw(ABC321 CDB672 PLE89);
my @array2 = qw(PLE89  ABC678 LMD789);

my %seen;

for my $item (@array1) {
    die "not a valid item: $item"
    	unless my ($key) = $item =~ /([A-Z]+)/;

    #we are using an array to hold the items in case
    #the same key shows up more than once in an array
    #this code can be simpler if you can guarantee 
    #that the keys are unique
    push @{$seen{$key}}, $item;
}

for my $item (@array2) {
    die "not a valid item: $item"
    	unless my ($key) = $item =~ /([A-Z]+)/;
    if (exists $seen{$key}) {
    	print "$item is in array1, it matches @{$seen{$key}}\n";
    } else {
    	print "$item is not in array1\n";
    }
}

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

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