2009-06-30 39 views
1

我是這個領域的新手。所以請好好放鬆一下。我有兩個數組:如何比較Perl中不同的數組元素?

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

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

我想比較這兩個不同數組的元素。但是,我只想用字母匹配字母。舉例來說,如果比較數組,$array[2]元素(PLE)應該與$array2[0](PLE)匹配,並且類似地$array1[0](ABC)應該與$array[1](ABC)匹配。我能夠一次做到這一點,但無法同時比較兩個數組的所有元素(即循環數組)。

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"; 
    } 

有關如何設置兩個數組同時循環的建議?

+0

W¯¯你想從'打印'長度\ n「; \'最後的聲明?你想打印字長還是使用長度函數? – Telemachus 2009-06-30 17:26:46

回答

4

您可以使用哈希作爲查找設備,並得到一個O(m+n)解決方案(其中m是陣列1的長度和n是數組2的長度)。

#!/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"; 
    } 
} 
2

語言不可知的建議將首先對兩個數組進行排序(應帶您O(n lg(n)),然後在線性時間內與兩個迭代器進行比較 如果性能不是問題,那麼保持簡單並且去成對比較的二次數量。 排序時,你還可以得到最終擺脫數字。