目前自己编写和网上查阅到比较方便的三种方法。
目录
1. 代码如下:
#! /usr/bin/perl
use warnings;
use strict;
open A, $ARGV[0] or die;
open B, $ARGV[1] or die;
open UNION, '>', "union.txt" or die;
open INTSEC, '>', "intsec.txt" or die;
open DIFF, '>', "diff.txt" or die;
open A_SPEC, '>', "a_spec.txt" or die;
open B_SPEC, '>', "b_spec.txt" or die;
my @a;
my @b;
while (<A>) {
chomp;
push @a, $_;
}
while (<B>) {
chomp;
push @b, $_;
}
my @union;#并集
my @diff; #差集
my @intsec;#交集
my @a_spec;
my @b_spec;
my %union;
my %intsec;
my %a;
my %b;
foreach (@a) {$union{$_}++; $a{$_}++;}
foreach (@b) {$union{$_}++; $b{$_}++;}
@union = keys %union;
foreach (@union) {
if (exists $a{$_} and $union{$_} == 1) {
push @a_spec, $_;}
elsif ($union{$_} == 1 and $b{$_} == 1) {
push @b_spec, $_;}
else {push @intsec, $_;}
}
@diff = (@a_spec, @b_spec);
print UNION (join "\n",@union);
print INTSEC (join "\n",@intsec);
print DIFF (join "\n", @diff);
print A_SPEC (join "\n", @a_spec);
print B_SPEC (join "\n", @b_spec);
2. 参考https://zk1878.iteye.com/blog/1019871,亲测非常好用,代码如下:
@a=('a'..'c',1..3);
@b=('A'..'C',1..3);
@union=();#并集
@diff=(); #差集
@isect=();#交集
foreach $e(@a,@b){
$union{$e}++&&$isect{$e}++;
}
@union=keys %union;
@isect=keys %isect;
@diff=grep {$union{$_}==1;} @union;
print (join ',',@union);
print "\n";
print (join ',',@isect);
print "\n";
print (join ',', @diff);
输出:
A,a,3,B,2,c,1,C,b
1,3,2
A,a,B,c,C,b
3. 参考http://www.omicsclass.com/article/350, 目测也非常简便,但没有试:
use Array::Utils qw(:all);
my @a = qw( a b c d );
my @b = qw( c d e f );
# symmetric difference
my @diff = array_diff(@a, @b);
# intersection
my @isect = intersect(@a, @b);
# unique union
my @unique = unique(@a, @b);
# check if arrays contain same members
if ( !array_diff(@a, @b) ) {
# do something
}
# get items from array @a that are not in array @b
my @minus = array_minus( @a, @b );
4. 参考https://blog.csdn.net/xudongxu27/article/details/25195297,没试,代码如下:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @a = (1,2,3,4,5,6,7,8,);
my @b = (1,9,0,4,15,6,12,8);
my %hash_a = map{$_=>1} @a;
my %hash_b = map{$_=>1} @b;
my %merge_all = map {$_ => 1} @a,@b;
my @a_only = grep {!$hash_b{$_}} @a;
my @b_only = grep {!$hash_a{$_}} @b;
my @common = grep {$hash_a{$_}} @b;
my @merge = keys (%merge_all);
print "A only :\n";
print Dumper(\@a_only);
print "B only :\n";
print Dumper(\@b_only);
print "Common :\n";
print Dumper(\@common);
print "Merge :\n";
print Dumper(\@merge);
以上内容若有侵权,请留言删除,谢谢。