Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: how to print key and value of hash as it is

by kzwix (Sexton)
on Jun 03, 2016 at 08:46 UTC ( [id://1164843]=note: print w/replies, xml ) Need Help??


in reply to how to print key and value of hash as it is

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.

  • Comment on Re: how to print key and value of hash as it is

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1164843]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (3)
As of 2024-04-20 01:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found