2013-08-26 75 views
0

我有兩個數組,所以我想從數組中的兩個數組中獲取相似的值。從Perl中的2個數組中獲取相似的值

這是數組:

my @a = qw(a e c d); 
my @b = qw(c d e f); 

請幫助我,我怎麼能拿在Perl.I類似的值在Perl

+0

所以你想用'C,d,e'在它的陣列? – KeepCalmAndCarryOn

+2

相關:[使用Perl比較兩個數組](http://stackoverflow.com/questions/2933347/comparing-two-arrays-using-perl) – rutter

回答

0

嘗試類似下面:

use strict; 
use Data::Dumper; 

my @a1 = qw(a e c d); 
my @b1 = qw(c d e f); 

my %seen; 
my @final; 

@seen{@a1} =(); # hash slice 

foreach my $new (@b1) { 
    push (@final, $new) if exists $seen{$new}; 
} 

print Dumper(\@final); 

輸出:

$VAR1 = [ 
      'c', 
      'd', 
      'e' 
     ]; 
+0

非常感謝你的幫助 – Developer

+0

很高興幫助你。 –

+0

你會解釋一下我們在@seen {@ a1} =()中做了什麼,然後是foreach – Developer

0

是新設的最終結果中包含有同時出現在數組中的元素:

#!/usr/bin/perl -w 
use strict; 
my @a = qw(a e c d); 
my @b = qw(c d e f); 
my @c; 

foreach my $x (@a) 
{ 
    foreach my $y (@b) 
    { 
     push @c, $x if ($x eq $y); 
    } 
} 

foreach (@c) {print $_."\n"}; 

輸出:

e 
c 
d 
0

一個常見的模式是映射爲可見元素的哈希和用grep查詢的其它陣列。

my @a = qw(a e c d); 
my @b = qw(c d e f); 

my %seen = map { $_ => 1 } @a; 
my @intersection = grep { $seen{$_} } @b; 

print @intersection; 
2

試試這個簡單的代碼:

my @a = qw(a e c d); 

my @b = qw(c d e f); 

foreach $my(@a){ 

     print "$my\n"; 
     if ((grep(/$my/,@b))){ 
       push @new,$my; 
     } 

} 
print "[email protected]";