perl用grep map求交集、并集、补集的实例代码
(编辑:jimmy 日期: 2024/11/27 浏览:3 次 )
复制代码 代码如下:
#!/usr/bin/perl
#
# 用grep map 获取两个列表的交集并集、补集
#
use strict;
my @a=("a","b","c","d","e");
my @b=("b","g","f","e");
print "列表a数据: @a \n";
print "列表b数据: @b \n";
my %a = map{$_ => 1} @a;
my %b = map{$_ => 1} @b;
my @c = map{$_ => 1} @a; # => 操作符起到了hash赋值的作用
# @a @b 交集
my @inter = grep {$a{$_}} @b; # 求交集
print "交集:@inter \n";
# @a,@b 并集
my %merge = map {$_ => 1} @a,@b; # 求并集
my @merge = keys (%merge);
print "并集:@merge \n";
# @a,@b的补集@ca,@cb,即@a和@b相对于@merge的补集
my @ca = grep {!$a{$_}} @merge;
my @cb = grep {!$b{$_}} @merge;
print "\@a的补集:@ca \n";
print "\@b的补集:@cb \n";
#!/usr/bin/perl
#
# 用grep map 获取两个列表的交集并集、补集
#
use strict;
my @a=("a","b","c","d","e");
my @b=("b","g","f","e");
print "列表a数据: @a \n";
print "列表b数据: @b \n";
my %a = map{$_ => 1} @a;
my %b = map{$_ => 1} @b;
my @c = map{$_ => 1} @a; # => 操作符起到了hash赋值的作用
# @a @b 交集
my @inter = grep {$a{$_}} @b; # 求交集
print "交集:@inter \n";
# @a,@b 并集
my %merge = map {$_ => 1} @a,@b; # 求并集
my @merge = keys (%merge);
print "并集:@merge \n";
# @a,@b的补集@ca,@cb,即@a和@b相对于@merge的补集
my @ca = grep {!$a{$_}} @merge;
my @cb = grep {!$b{$_}} @merge;
print "\@a的补集:@ca \n";
print "\@b的补集:@cb \n";
下一篇:perl 删除数组元素的几种方法小结