在Perl中,如何在不使用哈希的情况下在数组中找到重复值?

时间:2011-11-02 17:39:43

标签: perl

  

可能重复:
  What's the most efficient way to check for duplicates in an array of data using Perl?

在不使用哈希值的情况下在数组中查找重复值的最佳方法是什么

@A = ("foo","baz","bar","foo","baz","foo");

这是我的数组,如何只提取重复值,如:

foo
baz
@arr1 = (
          '2017554310',
          '2078991086',
          '2163824970',
          '2405206346',
          '2769562630',
          '2769562630',
          '3137026006',
          '3232651356',
          '3369962470',
          '3865302266',
          '4107452620',
          '4232926280',
          '5205689000',
          '5613613000',
          '6105668446',
          '6187592436',
          '6239350730',
          '6239350730',
          '7024698706',
          '7024698706',
          '7024698706',
          '7024698706',
          '7047088496',
          '7136929460',
          '7149705670',
          '7178455806',
          '7607491726',
          '7757710940',
          '8056423386',
          '8325522340',
          '8325522340',
          '8437352856',
          '8437352856',
          '8437352856',
          '9738570770'
        );

3 个答案:

答案 0 :(得分:5)

我不确定为什么你有 no hash 限制,或者没有外部模块。如果它是File::BasenameFile::Find等标准Perl模块之一,该怎么办?这些都带有标准的Perl安装。

你可以对阵列进行排序吗?

my @A = qw(foo baz bar foo baz foo);
my @B = sort @A;

现在@B等于qw*bar baz baz foo foo foo)。然后,您可以浏览此数组,看看前一个值是否等于最后一个值:

my @B = sort @A;
my $previous = pop @B;    #Just to start out:

foreach my $value (@B) {
   if ($previous eq $value) {  #Assuming strings only cause I can't use Scalar::Utils
      print qq("$value" is a duplicate!\n);
   }
   $previous = $value;
}

这将打印出"foo" is a duplicate的多个实例(每个副本一个)。如果您不想这样做,则必须进行测试,看看您之前是否打印过该声明。

答案 1 :(得分:2)

可能是马车,很可能毫无意义:

#!/usr/bin/perl

use strict; use warnings;

my @A = ("foo","baz","bar","foo","baz","foo");
@A = sort @A;

my @duplicates;
my $prev = pop @A;

while (defined(my $x = pop @A)) {
    if ($prev eq $x) {
        push @duplicates, $x;
        while (defined(my $y = pop @A)) {
            if ($y ne $x) {
                $prev = $y;
                last;
            }
        }
    }
    else {
        $prev = $x;
    }
}

use Data::Dumper;
print Dumper \@duplicates;

答案 2 :(得分:0)

使用'List :: MoreUtils'

perl -MList::MoreUtils=uniq -e '@A=("foo","baz","bar"","foo");print join " ", uniq(@A),"\n"'     
foo baz bar