Arijit Arijit - 5 months ago 14
Perl Question

How to access a hash in perl?

I have a perl data structure just like this

code for creating of the hash :
Here I am creating the hash from the database

undef %myhash;
while ( my @arry = $sth->fetchrow_array())
{
my @temp;

foreach my $line (@arry)
{
if ( defined $line )
{
push @temp, $line;
}
else
{
push @temp, -1; # set to -1 when any element is missing
}
}

push @features, [ @temp ];

push(@{$myhash{$temp[5]}->{$temp[7]}}, $temp[1], $line[2]);


}


structure will be like this

%myhash = (
1 => {
'scf1' => [
1,3,0,4,6,7,8,

],
'sef2' => [
10,15,20,30,
]
},
2 => {
'scf1' => [
10,3,0,41,6,47,81,
],
'scf3' => [
1,66,0,123,4,1,2435,33445,1
]
},
);


How does one access this kind of hash structure in Perl?

Answer

From your Data::Dumper dump, I see that you have a hash called %myhash. Each element in that hash contains a reference to another hash. And, each element in that inner hash contains a reference to an array.

Let's take your Data::Dumper, and restate it like this:

$myhash{1}->{sff1} = [1, 3, 0, 4, 6, 7, 8];
$myhash{1}->{sef2} = [10, 15, 20, 30];
$myhash{2}->{scf1} = [10, 3, 0, 41, 6, 47, 81];
$myhash{2}->{scf3} = [1, 66, 0, 123, 4, 2435, 33445, 1];

Same thing. It's just a bit more compact.

To print this out, we'll need to loop through each of these layers of references:

#
# First loop: The outer hash which is a plain normal hash
#
for my $outer_key ( sort keys %myhash ) {
    #
    #  Each element in that hash points to another hash reference. Dereference
    #
    my %inner_hash = %{ $myhash{$outer_key} };
    for my $inner_key ( sort keys %inner_hash ) {
        #
        # Finally, this is our array reference in the inner hash. Let's dereference and print
        #
        print "\$myhash{$outer_key}->{$inner_key}: ";
        my @array = @{ $myhash{$outer_key}->{$inner_key} };
        for my $value ( @array ) {
            print "$value";
        }
        print "\n";
    }
}
Comments