可能重複:
How do I find which elements in one array aren't in another?如何打印兩個陣列中不存在的元素?
@a=qw(one two three four five six);
@b=qw(zero one two three four seven);
我期望打印:
zero five six seven
這些元件不存在於兩個陣列。
可能重複:
How do I find which elements in one array aren't in another?如何打印兩個陣列中不存在的元素?
@a=qw(one two three four five six);
@b=qw(zero one two three four seven);
我期望打印:
zero five six seven
這些元件不存在於兩個陣列。
my %hash = map { $_ => 1 } @b;
while(my $el = shift @a)
{
print $el unless defined $hash{ $el };
$hash{ $el } = 0;
}
foreach(keys %hash)
{
print $_ if $hash{ $_ } == 1;
}
編輯:改變$ _到$ E1和在同時
use strict;
use warnings;
my @a=qw(one two three four five six);
my @b=qw(zero one two three four seven);
my %seen;
foreach my $a (@a) {
$seen{$a} = 1;
}
foreach my $b (@b) {
if (defined $seen{$b} and $seen{$b} == 1) {
$seen{$b} = -1;
} else {
$seen{$b} = 2;
}
}
foreach my $k (keys %seen) {
print "$k\n" if $seen{$k} != -1;
}
#!/usr/bin/perl
@a=qw(one two three four five six);
@b=qw(zero one two three four seven);
$words{$_}++ for (@a, @b);
while (($k, $v) = each %words) {
next if $v > 1;
print "$k ";
}
my %hash; $hash{$_}++ for @a,@b;
say join " ", grep { $hash{$_} == 1 } keys %hash;
謝謝親愛的。它可以通過此程序解決我的問題刪除 '打印'。 – CHE 2012-07-24 11:26:40