检查数组中的所有字符串是否都在第二个数组中

时间:2012-10-09 18:42:58

标签: perl

假设我有2个阵列

my @one = ("one","two","three","four","five");
my @two = ("three","five");

如何判断第二个数组中的所有元素是否都在第一个?

5 个答案:

答案 0 :(得分:4)

my %one = map { $_ => 1 } @one;
if (grep($one{$_}, @two) == @two) {
   ...
}

答案 1 :(得分:3)

另一种解决方法。

my %hash;
undef @hash{@two};  # add @two to keys %hash 
delete @hash{@one}; # remove @one from keys %hash 
print !%hash;       # is there anything left? 

我从这个perlmonks node

中偷走了这个想法

答案 2 :(得分:1)

use strict;

my @one = ("one","two","three","four","five");
my @two = ("three","five");

my %seen_in_one = map {$_ => 1} @one;

if (my @missing = grep {!$seen_in_one{$_}} @two) {
    print "The following elements are missing: @missing";
} else {
    print "All were found";
}

答案 3 :(得分:0)

另一种方法,不确定它比ikegami更好。还是TIMTOWTDI

#!/usr/bin/env perl

use strict;
use warnings;

use List::Util qw/first/;
use List::MoreUtils qw/all/;

my @one = ("one","two","three","four","five");
my @two = ("three","five");

if ( all { my $find = $_; first { $find eq $_ } @one } @two ) {
  print "All \@two found in \@one\n";
}

答案 4 :(得分:0)

从5.10开始,智能匹配运营商就会这样做。

my $verdict = !grep { not $_ ~~ @one } @two;

List::MoreUtils::all

my $verdict = all { $_ ~~ @one } @two;