Wednesday, March 9, 2011

Perl: accessing array from hash of arrays

Recently i came across an interesting problem in Perl.
Specifically, i was trying to access array from hash of arrays.

use strict;

my %oHash = ("one" => [1,2,3], "two" => [4,5,6], "three" => [7,8,9]);

OK. lets write function to output this hash.

sub print_hash {
    for my $key ( keys %oHash ) {
        print "$key: ";
        for my $i ( 0 .. $#{ $oHash{$key} } ) {
            print " $i = $oHash{$key}[$i]";
        }
        print "\n";
    }
}

Now if you call this sub you should see something like this:

three:  0 = 7 1 = 8 2 = 9
one:  0 = 1 1 = 2 2 = 3
two:  0 = 4 1 = 5 2 = 6

So printing is easy, but the problem is how to modify values of arrays (lets say array "one").

We need to create reference to array and here is magic part:

my $arr = \@{$oHash{"one"}};

Yes, that's it.

foreach(@{$arr}) {

    print $_ . "\n";
    $_ = 7; # modifying value
}

Done.