Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have run across a situation, which seems like it should have a better solution than I have come up with. Using the following hash:
$hash{key1}{value1} = 1; $hash{key1}{value2} = 2; $hash{key2}{value3) = 1;
I want to do something different for the keys that have only 1 hash refs after it. I can easily check whether that is the case using:
my $check = scalar keys %{$hash{$key}};
Where $key is passed to the function. However, I have no way of knowing what "valueN" is without doing something like:
forach my $k (keys %{$hash{$key}}) { # $k == the value i am looking for. }
It seems that there should be a more elegant way to pull the value of $k without using a foreach loop.

Replies are listed 'Best First'.
Re: determine a hash key
by broquaint (Abbot) on Nov 01, 2002 at 14:19 UTC
    A double grep should do the trick
    my @gt1 = grep { grep $_ > 1, values %{$hash{$_}} } keys %hash;
    Although, ultimately you will have to iterate through the hash (this way just does it internally).
    HTH

    _________
    broquaint

Re: determine a hash key
by artist (Parson) on Nov 01, 2002 at 18:49 UTC
    Hi
    If it helps, you might want to consider a different data structure.
    $hash{key1} = [1,2]; $hash{key2} = [1]; foreach (keys %hash){ $k = scalar @{$hash{$_}}; }

    Artist