请假数组的比较

请假数组的比较

偶想比较两个数组A,B,找出哪些元素只有数组A有,哪些元素只有B有
请问该如何实现
谢谢
grep

1) 先想想如何人工来做
2) 把 1) 的方法用计算机能懂的语言描述出来

#!/usr/bin/perl

use strict;
use warnings;

my @a = (1, 3, 4, 5, 6, 7, 8, 9, 9, 11, 13, 15);
my @b = (2, 4, 4, 6, 8, 10, 10, 12, 12, 14);

my %hash;

$hash{$_} = 1 for @a;
$hash{$_} = exists $hash{$_} ? ($hash{$_} == 2 ? 2 : 0) : 2 for @b;

print "$_ " for sort {$a <=> $b} grep { $hash{$_} == 1} keys %hash;
print "\n";
print "$_ " for sort {$a <=> $b} grep { $hash{$_} == 2} keys %hash;


改了改,数组里有重复项也可以处理了

简单点用这个模块
http://search.cpan.org/~dcantrell/Data-Compare-1.20/
use strict;

my @array1 = ("NS", "IE", "Opera","ww");
my @array2 = ("NS", "IE", "Opera","adfd");

my @array1_only;
my @array2_only;

@array1_only = grep {! filtering($_, @array2)} @array1;
@array2_only = grep {! filtering($_, @array1)} @array2;


print @array1_only,"\n";

print @array2_only,"\n";


sub filtering
{
my $self = shift;
my @temp = @_;

foreach (@temp)
{
return 1 if $_  eq $self;
}
}
output:

ww
adfd
大家都写了,俺也写个。呵呵
天天有这样的小问题,好入门,好练手
虽然其中一些代码看不懂,但也学习了
这样的问题,用shell 解决要难一点,用perl 解决来的容易
恨不得现在就与大家交流代码,但心有余而力不足,加快学习步骤!
#!/usr/bin/perl


use strict;
use warnings;

my @bb = (1, 3, 4, 5, 6, 7, 8, 9, 11, 13, 15);
my @aa = (2, 4, 6, 8, 10, 12, 14);

#求相同项

my @flag = map{ my $bb = $_; grep{ $_ eq $bb} @aa;} @bb;

print "@flag\n";

#求不相同项

for my $bb (@bb){
    print $bb," " unless(grep{ $_ eq $bb } @flag);
}

print "\n";

for my $aa (@aa){
    print $aa," " unless(grep{ $_ eq $aa } @flag);
}