-3

可能重复:
如何找到一个数组中的哪些元素不在另一个数组中?

@a=qw(one two three four five six);
@b=qw(zero one two three four seven);

我希望打印:

zero five six seven

这些元素在两个数组中都不存在。

4

4 回答 4

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 ";
}
于 2012-07-24T11:30:05.337 回答
0
my %hash; $hash{$_}++ for @a,@b;
say join " ", grep { $hash{$_} == 1 } keys %hash;
于 2012-07-24T11:40:07.590 回答
0
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; 
}
于 2012-07-24T11:21:36.537 回答
0
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;
}

编辑:将 $_ 更改为 $el 并在 while 中删除了 'print'

于 2012-07-24T11:20:17.477 回答