循环哈希参考perl的散列

时间:2015-03-01 05:40:32

标签: perl hash subroutine

我有一个哈希哈希,我将传递给子程序。在子例程中,我需要遍历哈希的哈希并根据外部哈希的密钥访问内部哈希的值。我在引用和解除引用哈希散列时遇到了问题。

这是我的代码。

use List::Util qw( min max );

#@testingWords is array of strings
foreach(@testingWords)
{
    #skip values that are '[' or ']' and move onto next value in array.
    if($_ eq '[' or $_ eq ']')
    {
        next;
    }
    #if value in array matches key in %trainingHashRaw (hash of hashes)pass key to getMax.
    if($trainingHashRaw{$_})
    {
        #key is $_, value is returned string from getMax
        #%trainingHashRelative is hash of hashes
        $testingHash{$_} = getMax($_, \%trainingHashRelative);
    }
}

sub getMax
{
    my $key = shift;
    my $hash = shift;
    my @max = ();
    my $max = 0;
    my $tag = "";

    for my $i(keys $hash)
    {
        for my $j(keys $hash->{$i})
        {
            if($key eq $i)
            {
                push(@max, $hash->{$i}->{$j});
            }
        }
        if(@max)
        {
            $max = max @max;    
        }
    }
    for my $i(keys $hash)
    {
        for my $j(keys $hash->{$i})
        {
            if($max == $hash->{$i}->{$j})
            {
                $tag = $j;
            }
        }
    }
    return $tag;
 }

1 个答案:

答案 0 :(得分:0)

您的数据结构应包含哪些内容尚不清楚。所以我为我认为你的意思做了一个例子。最大值可以出现多次,因此我会跟踪所有出现的情况。

use strict;
use warnings;

use List::Util qw( min max );
use Data::Dumper;

# for each outer key we want to get the max of values of the associated hashref
# outer_a: 3
# outer_b: 100
my %hash_of_hashes = (
    outer_a => {
        inner_a_x => 1,
        inner_a_y => 2,
        inner_a_z => 3,
    },
    outer_b => {
        inner_a_x => -100,
        inner_a_y => 100,
    },
    outer_c => {
        inner_a_x => 100,
        inner_a_y => 1,
    }
); 

my ($max_value, $keys_of_max_value) = get_max( \%hash_of_hashes );

print "The max value $max_value occured in ", join( ' ,',  @{$keys_of_max_value} ), ".\n";

sub get_max {
    my ($hoh_ref) = @_;  # reference to a hash of hashes

    # %tmp keeps track of the outer_key for the max of the inner values
    # %tmp = (
    #     3 => ['outer_a'],
    #     100 => ['outer_b', 'outer_c']
    # )
    my %tmp;
    while ( my ($outer_key, $inner_hashref) = each %{$hoh_ref} ) {

        my @inner_values = values %{$inner_hashref};
        my $max_inner_values = max( @inner_values );
        $tmp{$max_inner_values} ||= [];  # for clarity create the arref expiclitly
        push @{$tmp{$max_inner_values}}, $outer_key;
    }

    my $max_value = max( keys %tmp ); # 100

    return ( $max_value, $tmp{$max_value} ); # 100, ['outer_a', 'outer_b'] 
}