简体   繁体   English

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

[英]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 not another:我有两个 arrays 并且我想找到在一个数组中但不在另一个数组中的元素:

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:将第二个数组的元素放入 hash 中,以便有效检查特定元素是否在其中,然后仅过滤第一个数组中不在第二个数组中的元素:

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

You can use a cpan module called List::Compare .您可以使用名为List::Compare的 cpan 模块。

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

Use hash as a lookup table.使用 hash 作为查找表。 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 .有关更多信息,请参阅Perl Cookbook中的配方 4.8。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM