in reply to Re^3: hash help
in thread hash help

thanks for the help, I have one more questions, how would you process each vaules in hash of array, like I want add 5+8+9 then add to push to aaa_1 4 5 8 9 22

can you just breif me how does it get popualted into single hash

Replies are listed 'Best First'.
Re^5: hash help
by Marshall (Canon) on Jul 13, 2009 at 00:03 UTC
    The structure that I demonstrated is a Hash of Array. A hash can only have one value for each key, BUT that value can be a pointer to another data structure, in this case, an anonymous array. To initialize an @variable, you would normally have something like: my @variable =(4,5,6); That puts 3 things into @variable. If you have @variable =[4,5,6];, that puts ONE thing into @variable, a POINTER an array with 3 things in it. That array with the 3 things has no given name and is called an anonymous array.

    All of the things that you can do with an array apply in this situation: simple assignment, push, pop, shift, unshift, etc.. Below I showed some other code with a more explicit looking assignment with the square brackets for the anonymous array. It looks a bit "funny" because this is a assignment of a value to a hash key, but the principle is the same as simple array.

    So to sum up all things in an array and push the total onto the array, we do it just like if this was a simple @var! See the code below.

    I will point out that when you deference a multi-dimensional thing with a subscript, you need an extra pair of {}, hence  @{$hash{'aaa_1'}}.

    hope this answers your question...

    #!/usr/bin/perl -w use strict; my %hash; $hash{'aaa_1'}=[9, 8,7,6]; print "aaa_1 is : @{$hash{'aaa_1'}}\n"; #prints aaa_1 is : 9 8 7 6 my $array_ref = $hash{'aaa_1'}; #another way... print "@$array_ref\n"; #de-references array ref into array #prints 9 8 7 6 foreach my $num (@$array_ref) #another way { print "a num is: $num\n"; } #prints this... #a num is: 9 #a num is: 8 #a num is: 7 #a num is: 6 ################# $hash{'aaa_1'}=[]; #clears anon array push @{$hash{'aaa_1'}},(4,5,8,9); print "aaa_1 is : @{$hash{'aaa_1'}}\n"; #prints aaa_1 is : 4 5 8 9 ############### my $sum=0; foreach my $num (@{$hash{'aaa_1'}}) { $sum+=$num; } push @{$hash{'aaa_1'}}, $sum; print "aaa_1 is now : @{$hash{'aaa_1'}}\n"; #prints aaa_1 is now : 4 5 8 9 26