I think how to use each %hash has been well covered. However, I point out that iterating of the keys %hash is far, far more common. Usually what is desired is some kind of ordering of the printout, typically some kind of sorted order. (also shown below).
Update: added another test case to show that both the key and the value windup in @k in this situation while ( my(@k, $v, $anything) = each %hash)
Also worthy of note is that the order of the hash will vary between runs using recent Perl's. Run my code a couple of times and you will see. The function that calculates the internal binary hash key has a per run "fudge factor" - there are some security and other performance issues related to this behaviour. Bottom Line: Do not count on the each %hash function processing in the same order each run because it will not! This is one reason why using some kind of sort function upon keys is much,much more common (at least in my code) than using the each %hash function.
#!/usr/bin/perl use strict; use warnings; my %hash = qw ( 6 18 50 150 3 9 7 21 91 273 9 27 1 3 4 12 34 102 89 267 76 228 ); foreach my $key (sort {$a <=> $b} keys %hash) #numeric sort (not defau +lt alpha sort) { print "$key=>$hash{$key}\n"; } print "\n"; my @keys = keys %hash; my @values = values %hash; print "below keys and values \"line up\" but not sure that is guarante +ed:\n"; printf "%3i ",$_ foreach @keys; print "\n"; printf "%3i ",$_ foreach @values; print "\n\n"; #show that both the key and the value will wind #up in @k in this situation.. while ( my(@k, $v, $anything) = each %hash) { print "\$v is undefined: \@k is: " if !defined $v; printf "%3i ",$_ for @k; print "\n"; } __END__ 1=>3 3=>9 4=>12 6=>18 7=>21 9=>27 34=>102 50=>150 76=>228 89=>267 91=>273 below keys and values "line up" but not sure that is guaranteed: 9 4 76 50 6 89 3 1 34 91 7 27 12 228 150 18 267 9 3 102 273 21 $v is undefined: @k is: 9 27 $v is undefined: @k is: 4 12 $v is undefined: @k is: 76 228 $v is undefined: @k is: 50 150 $v is undefined: @k is: 6 18 $v is undefined: @k is: 89 267 $v is undefined: @k is: 3 9 $v is undefined: @k is: 1 3 $v is undefined: @k is: 34 102 $v is undefined: @k is: 91 273 $v is undefined: @k is: 7 21
In reply to Re: Output of hash
by Marshall
in thread Output of hash
by catfish1116
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |