![](/img/trans.png)
[英]compare two arrays in javascript and delete the object that both arrays have
[英]Compare Arrays and Delete Arrays
我下面有三组(数组),我需要对它执行这样的操作( (AB)UC )
。 有人可以在Perl中做到这一点吗? 这是我的代码,我可以检查是否为A的B子集,但无法执行“ AB”:
my @array = (MAJOR,MINOR,MM,DD,YY);
my @exclude = (MM,MINOR,YY);
my @include = (LICENSE,VALID);
foreach (@exclude) {
if ( $_ ~~ @array ) {
print "\n $_ is defined in variables and it will be excluded \n";
@array = grep {!/\$_/} @array;
print "@array \n";
}
else {
print "\n $_ is not defined under variables please check the files \n";
exit 100;
}
}
foreach (@array){
print "$_ \n";
}
我怀疑grep操作(即删除操作)的逻辑有问题。
grep的一个问题是,外循环中的$_
在grep块内重新定义为@array
每个元素。 您需要使用其他名称。 另外,您的正则表达式缺少锚点; 但是,可以使用字符串不等式代替正则表达式。 尝试这个:
my @array = qw(MAJOR MINOR MM DD YY);
my @exclude = qw(MM MINOR YY);
my @include = qw(LICENSE VALID);
foreach my $e (@exclude) {
if ( $e ~~ @array ) {
print "\n $e is defined in variables and it will be excluded \n";
@array = grep {$e ne $_} @array;
print "@array \n";
} else {
print "\n $e is not defined under variables please check the files \n";
exit 100;
}
}
使用严格的警告来提醒您Perl的许多陷阱。
散列是在perl中表示集合的最自然的方法。
use strict;
use warnings;
my @array = ('MAJOR','MINOR','MM','DD','YY');
my @exclude = ('MM','MINOR','YY');
my @include = ('LICENSE','VALID');
my %set;
# add @array to set
@set{@array} = ();
# remove @exclude
delete @set{@exclude};
# add @include
@set{@include} = ();
# array of elements resulting
my @result = sort keys %set;
您可以使用一set
来执行此类操作。 我使用了一个非标准模块Set::Scalar
来帮助我:
#!/usr/bin/env perl
use warnings;
use strict;
use Set::Scalar;
my @array = qw(MAJOR MINOR MM DD YY);
my @exclude = qw(MM MINOR YY);
my @include = qw(LICENSE VALID);
my $array_set = Set::Scalar->new(@array);
my $exclude_set = Set::Scalar->new(@exclude);
my $include_set = Set::Scalar->new(@include);
my $result = $array_set->difference($exclude_set)->union($include_set);
use Data::Dumper;
print Dumper @$result;
像这样运行:
perl script.pl
产生:
$VAR1 = 'VALID';
$VAR2 = 'MAJOR';
$VAR3 = 'DD';
$VAR4 = 'LICENSE';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.