Quote:
Originally Posted by vinodkaushik
Hi,
I have written below code to compare the files but it is showing all the files in an array2
Code:
for my $i (@array2) {
print "$i\n" if grep {$i ne $_} @array1;
}
|
Off course.
grep {$i ne $_} @array1 always returns a list of files that are not equal to $i, so is evaluated true and thus $i prints.
What you want to do is this :
Code:
my @missing = grep { my $x = $_; not grep { $x eq $_ } @array1 } @array2;
@missing contains everything from @array2 that is not in @array1.
Or if you want to do it with a loop :
Code:
for my $i (@array2) {
print "$i\n" if not grep {$i eq $_} @array1;
}
EDIT :
If you want to see what grep actually returns in your script, execute :
Code:
#! /usr/bin/perl -w
my @array1 = ("file1","file2","file3","file6");
my @array2 = ("file4","file3","file1","file5");
for my $i (@array2) {
print grep {$i ne $_} @array1;
print "\n";
}
You realize immediately why it doesn't work.