Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl 检查数组中的所有字符串是否在第二个数组中_Perl - Fatal编程技术网

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

Perl 检查数组中的所有字符串是否在第二个数组中,perl,Perl,假设我有两个数组 my @one = ("one","two","three","four","five"); my @two = ("three","five"); 如何判断第二个数组中的所有元素是否都在第一个数组中?另一种方法,不确定它是否比ikegami的好。仍然是蒂姆托蒂 my %one = map { $_ => 1 } @one; if (grep($one{$_}, @two) == @two) { ... } #!/usr/bin/env perl use st

假设我有两个数组

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

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

另一种方法,不确定它是否比ikegami的好。仍然是蒂姆托蒂

my %one = map { $_ => 1 } @one;
if (grep($one{$_}, @two) == @two) {
   ...
}
#!/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";
}

从5.10开始,智能匹配操作员将执行此操作

my $verdict = !grep { not $_ ~~ @one } @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? 

我是从这个

中偷来这个想法的,对不起,我是perl新手。你能告诉我这些行在做什么吗。1创建一个散列。在哈希中为@one中的每个值创建一个元素。数组中的值用作哈希中的键。2统计@two中作为%one中键的元素数。然后,它将该计数与@two中的元素数进行比较。由于OP已澄清至少一个数组可以包含重复的成员,因此此解决方案可能不适用。@pilcrow,在任意一个/两个数组中都可以使用重复的成员。数组是否保证为唯一元素集,或者你能不能举个例子@one=one,one,one,two,one?请澄清你的要求。你认为“A”、“A”、“B”中的所有元素都在“A”、“B”中吗?是的,我只关心文件数组中的所有“文件”都与我的RCV中所有文件的列表相比,当我尝试第一个文件时,得到了一个编译错误。它说它接近$\uu~~。我正在使用Perl5.8。8@Bill ... 在5.10之前,这个解决方案虽然代码优雅,但它是OM*N,也就是说它必须执行@one*@two操作。如果@one和@two都有5个元素,那就是25个操作。如果他们有10个,那就是100个手术。20美元,400美元。除了非常小的列表,不要使用它。这本质上是@Axeman的解决方案。Smart match将比first快,但它们都是OM*N。我猜你的平均值是OM/2*N,first只需搜索数组的一半,但first vs~的较慢性能将否定这一点。是的,正如我的帖子可能指出的,我开始沿着List::MoreUtils路径发布,以确保完整性;我并不惊讶这不是最好的。尽管我的解决方案是在@axemans之前发布的,但我声称他的基本上和我的一样:-P
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";
}