如何在Perl中找到一个数组中的元素而不是另一个数组中的元素?

时间:2011-07-16 01:27:02

标签: arrays perl

我有两个数组,我想找到一个数组而不是另一个数组的元素:

例如:

@array1 = ("abc", "cde", "fgh", "ijk", "lmn")
@array2 = ("abc", "fgh", "lmn")

我最终需要:

@array3 = ("cde", "ijk")

6 个答案:

答案 0 :(得分:15)

将第二个数组的元素放入散列中,以便有效地检查特定元素是否在其中,然后过滤第一个数组以查找那些不在第二个数组中的元素:

my %array2_elements;
@array2_elements{ @array2 } = ();
my @array3 = grep ! exists $array2_elements{$_}, @array1;

答案 1 :(得分:5)

答案 2 :(得分:2)

my @array3;
foreach my $elem ( @array1 )
{
    if( !grep( $elem eq $_, @array2 ) )
    {
        push( @array3, $elem );
    }
}

答案 3 :(得分:1)

您可以使用名为List::Compare的cpan模块。

use List::Compare;
    my $lc = List::Compare->new(\@array1,\@array2);
    my @newarray = $lc->get_symdiff;

答案 4 :(得分:1)

使用hash作为查找表。它的键是第二个数组的元素,值不重要:

#!/usr/bin/env perl
use strict;
use warnings;

my @array1 = ( "abc", "cde", "fgh", "ijk", "lmn" );
my @array2 = ( "abc", "fgh", "lmn" );

my @array1only;

# build lookup table
my %seen;
foreach my $elem (@array2) {
    $seen{$elem} = 1;
}

# find elements present only in @array1
foreach my $elem (@array1) {
    push @array1only, $elem unless $seen{$elem};
}

print "Elements present only in \@array1: ", join( ", ", @array1only ), "\n";

有关详情,请参阅Perl Cookbook中的食谱4.8。

答案 5 :(得分:0)

my %total;
$total{$_} = 1 for @array1; 
delete $total{$_} for @array2; 
my @diff = keys %total;