daf*_*dil 4 arrays algorithm perl comparison
我需要比较两个数组并得到差异。
背景:
第一个阵列将列出文件夹中的文件。
第二个数组将读取文件的内容并存储在数组中。
第一个数组的输出将是
a
b
c
d
e
Run Code Online (Sandbox Code Playgroud)
第二个数组的输出将是
a
b
c
e
Run Code Online (Sandbox Code Playgroud)
我怎样才能比较得到差异的那两个数组?我想要的结局输出是
d
Run Code Online (Sandbox Code Playgroud)
这是代码:
#!/usr/bin/perl
use strict;
use warnings;
my $list = "experiment.sv";
my $path = "../../../folder1/";
my $filelist;
open ( OUTFILE, ">output.txt" );
main ();
close OUTFILE;
sub main {
my @array1;
opendir ( DIR, $path ) || die "Error in opening dir $path\n";
while ( $filelist = readdir (DIR) ) {
next if ( $filelist =~ s/\.//g); #/
push @array1, $filelist;
}
closedir(DIR);
my @array2;
open( my $fh, "<", "$path/$list") or die "Failed to open file: $!\n";
while(<$fh>) {
push @array2, $_;
}
close $fh;
my @result;
foreach my $array2 (@array2) {
foreach my $array1 (@array1) {
if ($array1 !~ /$array2/ ) {
push @result, "$array1\n";
}
}
}
print OUTFILE "",@result;
}
Run Code Online (Sandbox Code Playgroud)
有几种方法可以做到这一点,这还取决于实际需要什么。
为每个数组使用辅助哈希,以将存在检查减少为查找
use warnings;
use strict;
use feature 'say';
sub diff_arys {
my ($ra1, $ra2) = @_;
my %in_a1 = map { $_ => 1 } @$ra1;
my %in_a2 = map { $_ => 1 } @$ra2;
my @not_in_one = grep { not exists $in_a1{$_} } @$ra2;
my @not_in_two = grep { not exists $in_a2{$_} } @$ra1;
return (@not_in_one ? \@not_in_one : undef),
(@not_in_two ? \@not_in_two : undef);
}
my @ary1 = 'a'..'e'; # a,b,c,d,e
my @ary2 = ('a'..'d', 'z'); # a,b,c,d, z
my ($not_in_one, $not_in_two) = diff_arys(\@ary1, \@ary2);
say "@$not_in_one" if $not_in_one;
say "@$not_in_two" if $not_in_two;
Run Code Online (Sandbox Code Playgroud)
版画
ž Ë
This finds difference both ways, elements in one array but not in the other. If you know for fact that you only need it for one "direction," to identify things that are in the first array but not in the second (as it seems from the question), then adjust the sub for that and code gets simpler.
Note the choice for the interface: Return undef if no difference is found, an arrayref otherwise.
There are good modules for this kind of work. A rather comprehensive one is List::Compare. There are also Array::Utils and Array::Compare, and yet more. And then there are more complex tools that can also be used for this, like Algorithm::Diff.
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |