Syntactic Confectionery Delight | |
PerlMonks |
Re: how to print key and value of hash as it isby kzwix (Sexton) |
on Jun 03, 2016 at 08:46 UTC ( [id://1164843]=note: print w/replies, xml ) | Need Help?? |
Err... I'm not sure of what you're going for, with your code. However, if you wish to print the contents of your hash in the order of its keys, then: for my $key (sort keys %hash) { print "The key '$key' is associated to the value '$hash{$key}'\n"; } If you wish to print the contents of your hash in the order of its CONTENTS (not of its keys), then yes, you need a custom sort method. The following code is merely an adaptation of an example found on the Perl "sort" documentation page: for my $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) { print "The key '$key' is associated to the value '$hash{$key}'\n"; } However, please consider performance when doing so: If you merely need to access it once, then the sort method is fine. If you need it ordered by value, and accessed a lot of times, then a reverse hash might be the solution. In this case, if you may have multiple instances of the same value, you might have collisions, and thus, will need to store references to lists containing the different values.
In Section
Seekers of Perl Wisdom
|
|