-3

假设我有 2 个数组

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

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

4

5 回答 5

4
my %one = map { $_ => 1 } @one;
if (grep($one{$_}, @two) == @two) {
   ...
}
于 2012-10-09T18:49:45.737 回答
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 节点偷了这个想法

于 2012-10-09T21:18:03.230 回答
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";
}
于 2012-10-09T22:22:45.093 回答
0

自 5.10 起,智能匹配运算符将执行此操作。

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

或与List::MoreUtils::all

my $verdict = all { $_ ~~ @one } @two;
于 2012-10-09T19:30:52.520 回答
0

另一种方法,不确定它是否比 ikegami 的更好。仍然是 TIMTOWDI

#!/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";
}
于 2012-10-09T19:12:10.157 回答