假设我有 2 个数组
my @one = ("one","two","three","four","five");
my @two = ("three","five");
如何判断第二个数组中的所有元素是否都在第一个?
假设我有 2 个数组
my @one = ("one","two","three","four","five");
my @two = ("three","five");
如何判断第二个数组中的所有元素是否都在第一个?
my %one = map { $_ => 1 } @one;
if (grep($one{$_}, @two) == @two) {
...
}
还有另一种解决方法。
my %hash;
undef @hash{@two}; # add @two to keys %hash
delete @hash{@one}; # remove @one from keys %hash
print !%hash; # is there anything left?
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";
}
自 5.10 起,智能匹配运算符将执行此操作。
my $verdict = !grep { not $_ ~~ @one } @two;
my $verdict = all { $_ ~~ @one } @two;
另一种方法,不确定它是否比 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";
}