How to find and count duplicate values ​​in a perl hash

I need to find duplicate values ​​in the perl hash, and then print the key / value pair and the associated duplicate counter, if that number is 1.

(I could leave a sample code for what I tried, but it would just lead to mass confusion and possibly uncontrollable laughter, and I really hope to do this through life with some semblance of self-esteem.)

The hash key / value will look like this:

%hash = qw('FHDJ-124H' => 'hostname1', 'HJDHUR-87878' => 'hostname2', 'HGHDJH-874673' => 'hostname1');

My desired result:

2 duplicates found for hostname1
    FHDJ-124H
    HGHDJH-874673

Using perl 5.6 on Solaris 10. A tightly controlled production environment where updating or downloading perl mods is not acceptable. (The change request for the transition to 5.8 is about 6 months).

Many thanks!

+4
source share
4 answers

- (/) , (/).

, , ( ). , . I.e., - (value/[key1, key2, key3...])

my %hash = ( key1 => "one", key2 => "two", key3 => "one", key4 => "two", key5 => "one" );
my %counts = ();
foreach my $key (sort keys %hash) {
    my $value = $hash{$key}; 
    if (not exists $counts{$value}) {
        $counts{$value} = [];
    }
    push $counts{$value}, $key;
};

$counts , , $counts {$ value} > 1

+6

,

#!/usr/bin/perl
use strict;
use warnings;
my %hash = ('FHDJ-124H' => 'hostname1', 'HJDHUR-87878' => 'hostname2', 'HGHDJH-874673' => 'hostname1');
my %reverse;

while (my ($key, $value) = each %hash) {
    push @{$reverse{$value}}, $key;
}

while (my ($key, $value) = each %reverse) {
    next unless @$value > 1;

    print scalar(@$value), " duplicates found \n @$value have the same key $key\n";     

}
+4

:

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dump qw(dump);

my %h = (a=>'v1', b=>'v2', c=>'v1', d=>'v3', e=>'v3');
my %r;
while(my($k,$v)=each%h){
    push @{$r{$v}}, {$k=>$v};
}
dump %r;

:

(
  "v1",
  [{ c => "v1" }, { a => "v1" }],
  "v2",
  [{ b => "v2" }],
  "v3",
  [{ e => "v3" }, { d => "v3" }],
)
+2

, - :

my @values=sort(values(%hash));
my @doubles=();
my %counts=();



foreach my $i (0..$#values)
{
    foreach my $j (($i+1)..$#values)
    {
        if($values[$i] eq $values[$j])
        {
            push @doubles,$values[$i];
            $counts{$values[$i]}++;

        }
    }
}

foreach(@doubles)
{
    print "$hash{$_}, $_, $counts{$_}\n";
}

( ), , , .

+1

All Articles