开发者

How can I find elements that are in one array but not another in Perl?

I have two arrays and I want to find elements that are in one array but开发者_JS百科 not another:

ex:

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

I need to end up with:

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


Put the elements of the second array into a hash, for efficient checking to see whether or not a particular element was in it, then filter the first array for just those elements that were not in the second array:

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


See How do I compute the difference of two arrays? How do I compute the intersection of two arrays? in perlfaq4.


You can use a cpan module called List::Compare.

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


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


Use hash as a lookup table. Its keys are the elements of the second array, values don't matter:

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

For more see recipe 4.8 in Perl Cookbook.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜