CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
reversing a hash

 



jazzo
Novice

Aug 27, 2012, 5:21 AM

Post #1 of 5 (1068 views)
reversing a hash Can't Post

Hi all, I wonder what happens when we reverse a hash.
Given this code

Code
 
my %where=(
Gary => "Dallas",
Lucy => "Exeter",
Ian => "Reading",
Samantha => "Oregon"
);
my %who = reverse %where;

what happens to the hash after it has been reversed?
I mean which way is it reversed? Do keys become values or does the order change?
thanks


shawnhcorey
Enthusiast


Aug 27, 2012, 6:17 AM

Post #2 of 5 (1067 views)
Re: [jazzo] reversing a hash [In reply to] Can't Post

See:

Code
perldoc -q 'How do I look up a hash element by value?'


__END__

I love Perl; it's the only language where you can bless your thingy.

Perl documentation is available at perldoc.perl.org. The list of standard modules and pragmatics is available in perlmodlib.

Get Markup Help. Please note the markup tag of "code".


Laurent_R
Veteran / Moderator

Aug 27, 2012, 6:59 AM

Post #3 of 5 (1065 views)
Re: [jazzo] reversing a hash [In reply to] Can't Post

Hashes have no particular order (the order is internal to the hash), a reverse on a hash will do nothing, the hash will remain unchanged.


FishMonger
Veteran / Moderator

Aug 27, 2012, 8:13 AM

Post #4 of 5 (1063 views)
Re: [jazzo] reversing a hash [In reply to] Can't Post

An easy way to find out what happens is to print out both hashes, which would have taken less time than asking the question.


Code
use Data::Dumper; 

my %where=(
Gary => "Dallas",
Lucy => "Exeter",
Ian => "Reading",
Samantha => "Oregon"
);
my %who = reverse %where;

print Dumper \%who, \%where;



jazzo
Novice

Aug 27, 2012, 12:47 PM

Post #5 of 5 (1059 views)
Re: [FishMonger] reversing a hash [In reply to] Can't Post

thanks, I tried that but it looks like I need to install something, is there a package or something:

Code
 
antobbo@antobbo-xps17-ubuntu:~$ perldoc -q 'How do I look up a hash element by value?'
You need to install the perl-doc package to use this program.

Ah sorry I forgot to add this: I have printed both the hashes, the normal one which produced

Code
Lucy Exeter Samantha Oregon Gary Dallas Ian Reading

and the reversed one which gave

Code
Oregon Samantha Exeter Lucy Reading Ian Dallas Gary

so it appears as if reversing a hash swaps the value and keys?!


(This post was edited by jazzo on Aug 27, 2012, 1:08 PM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives