如何测试数组中是否重复某个值?

时间:2017-02-14 01:52:04

标签: perl

我正在做一个以数字列表作为参数的子程序。我想做的是检查该列表中是否有重复值。如果有重复的数字,请打印一条消息并停止该程序。如果没有重复的数字,继续执行。

例如:

if (there_is_number_repeated){
    print "There is a number repeated";}
else{
    run this code...}

我尝试使用该列表的值创建哈希,然后检查是否存在值> 1

    use strict;
    use warnings;

sub name_subroutine{
    my (@numbers)=@_;
    my $n=scalar(@numbers);

    my %table=();

    foreach my $i(@numbers){
    if (exists $tabla{$i}){
        $tabla{$i}+=1;}
    else{
        $tabla{$i} = 1;
    }
my @values = values %tabla;
}
}

我不知道在哪里继续。有没有办法以业余的方式做到这一点?我是Perl的新手。

谢谢!

2 个答案:

答案 0 :(得分:8)

我会这样做:

my %uniq;
if ( grep ++$uniq{$_} > 1, @numbers ) {
     # some numbers are repeated
}

在您现有的代码中(有一些更正):

my %table=();

foreach my $i(@numbers){
    if (exists $table{$i}){
        $table{$i}+=1;}
    else{
        $table{$i} = 1;
    }
}
my @values = values %table;

你不需要检查存在;如果不存在,+= 1++会将其设置为1。并且你不想要这些值(那些只是每个数组值被发现的次数),你想要的是键,特别是那些值为>的键。 1:

my @repeated = grep $table{$_} > 1, keys %table;

答案 1 :(得分:0)

my @arr = @_; 
my $count = @arr;
for(my $i=0;$i<$count;$i++)
{
    my $num = $arr[$i];
    for(my $j=0; $j<$count,$j!=$i; $j++)
    {
        if($num == $arr[$j])
        {
           print "\n$num is repeated";
           last;
        }  
    }
}  

试过并测试过。欢呼声。