I have an hash map like this
my $name = \'AUS\'; #dynamic values
my %hash = { \'a\'=>{
\'x\'=> {
\'1\' =>\'US
if I understand correctly you want something like this:
use strict;
use warnings;
my $name = 'AUS'; #dynamic values
my %hash = ( 'a'=>{
'x'=> {
'1' =>'US',
'2' =>'UK'
},
'y'=>{
'1' =>'AFRICA',
'2' =>'AUS'
}
},
'b'=>{
'x' =>{
'1' =>'US',
'2' =>'UK'
}
}
);
my @val = grep {$_ eq $name} map {my $x=$_; map {my $y=$_; map {$hash{$x}->{$y}->{$_}} keys %{$hash{$x}->{$_}}} keys %{$hash{$_}}} keys %hash;
if(@val == 0) {
print "$name not found";
}
elsif(@val == 1) {
print "$name is unique";
}
else {
print "$name is not unique";
}
There's no magic bullet here. You have to traverse your hash and inspect each value. There's a variety of approaches to doing this, and which you use is rather dependent on how your hash-source gets populated.
A recursive solution would be:
#!/usr/bin/env perl
use strict;
use warnings;
my $name = 'AUS';
use Data::Dumper;
my %hash = ( 'a'=>{
'x'=> {
'1' =>'US',
'2' =>'UK'
},
'y'=>{
'1' =>'AFRICA',
'2' =>'AUS'
}
},
'b'=>{
'x' =>{
'1' =>'US',
'2' =>'UK'
}
}
);
my %count_of;
sub traverse {
my ( $input_hash ) = @_;
foreach my $sub ( values %{$input_hash} ) {
if (ref $sub) {
traverse ($sub);
}
else {
$count_of{$sub}++;
}
}
}
traverse (\%hash);
print Dumper \%count_of;
print "$name is unique\n" if $count_of{$name} == 1;
Because this is recursive, it will walk to any 'depth' of the hash, but that might not be entirely appropriate for you use-case.
However the fact that you're talking about columns, suggests to me that this hash is being populated from elsewhere - I would suggest you look at that population process, because it's quite likely that's a better place to start picking out particular counts-of-values.
If you need a more versatile lookup table:
my @unique_elements = grep { $count_of{$_} == 1 } sort keys %count_of;
print Dumper \@unique_elements;
my %is_unique = map { $_ => 1 } @unique_elements;
print Dumper \%is_unique;
print "$name is unique\n" if $is_unique{$name};