![](/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.