我有兩個數組,所以我想從數組中的兩個數組中獲取相似的值。從Perl中的2個數組中獲取相似的值
這是數組:
my @a = qw(a e c d);
my @b = qw(c d e f);
請幫助我,我怎麼能拿在Perl.I類似的值在Perl
我有兩個數組,所以我想從數組中的兩個數組中獲取相似的值。從Perl中的2個數組中獲取相似的值
這是數組:
my @a = qw(a e c d);
my @b = qw(c d e f);
請幫助我,我怎麼能拿在Perl.I類似的值在Perl
嘗試類似下面:
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'
];
是新設的最終結果中包含有同時出現在數組中的元素:
#!/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
你也可以嘗試http://vti.github.io/underscore-perl下劃線JS的克隆。你可以做2個陣列的交叉 - >http://vti.github.io/underscore-perl/#intersection
use Underscore;
_->intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
# [1, 2]
一個常見的模式是映射爲可見元素的哈希和用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;
試試這個簡單的代碼:
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]";
所以你想用'C,d,e'在它的陣列? – KeepCalmAndCarryOn
相關:[使用Perl比較兩個數組](http://stackoverflow.com/questions/2933347/comparing-two-arrays-using-perl) – rutter