Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hash of Lists Problem

Status
Not open for further replies.

perlfan

Technical User
Apr 18, 2002
17
US
I've been struggling with the following code now and am about to scream. Can someone please tell me how to pull a list out of a hash that contains lists?

my %MsgContents = (
A => [1, 2, 3],
B => [4, 5, 6]
);
my $single = $MsgContents{B}[0];
print $single; # prints 4 as expected

#my @hashlist = values %{$MsgContents{B}}; #Doesn't Work!
#print @hashlist;

#my @hashlist = @{%{$MsgContents{B}}}; #Doesn't Work!
#print @hashlist;

 
Try this...

Code:
push @hashlist foreach values %MsgContents;

This will put [1,2,3] onto $hashlist[0], [4,5,6] onto $haslist[1], and so on, although it might not be in an order that you expect.
 
Well, after stepping away fron the problem for a little while and then referring to the bible as written by Larry Wall I happened on a solution.

my @hashlist = @{$MsgContents{A}};

 
That works...? If I were to put the actual list in there, that would be like saying...
my @hashlist = @{[1,2,3]};

I don't understand how that would work. How can you give a list as the name of an array? Wouldn't that array not exist?
 
There is a great resource for this sort of thing. Check out the perl man page called perldsc (Data Structures Cookbook). It will show you how to do hashes of lists, hashes of hashes, arrays of hashes, arrays of arrays, and all kinds of cute stuff. Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard. [dragon]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top