in reply to Re^4: hash help
in thread hash help
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
|
|---|