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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Retreiving data from a hash in order entered?

Status
Not open for further replies.

sloppyhack

Technical User
Apr 17, 2001
111
US
I have created a hash and edited the values in the hash. I now need to get the values back out of the hash in the order they were entered. I can get the values using the values function but they are not in the original order. Any ideas?
 
It can't be done. The whole point of a hash is to randomly access a value based on a key, and for that the data is stored in "buckets". You can't even get the keys in any particular order unless you sort them yourself (i.e. sort keys %hash), and entry-order is not an option. If you really need the values in the order entered then maybe you shouldn't be using a hash. Otherwise, what I'd suggest is to push the keys in an array as you get them, bofore you create the hash values. Then pop the key back out of the array and use them to access the values in the hash.
Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
I disagree with tsdragon.

There is a module called Tie-IxHash which allows you to recall the hashes in the order that they were entered.

I suppose you could then create some mechanisme to get it in the reversed order (maybe something is already build in the module, but you would have to check).

Thierry.



 
It is a little tedious, but in simple situations, you can simply build a parallel array. When you add something to the hash add it to the array, then use the array elements to retrieve values from the hash. Not, terribly elegant, but it works.

.....
while (....getting keys and values for the hash....)
{
$hash{key} = value;
push @keys,key;
}

foreach $key (@keys)
{
my $value = $hash{$key};
print "The next element is $value\n";
}
....

Obviously, this gets messy quickly if you are not dealing with a fairly simple situation.
HTH


keep the rudder amid ship and beware the odd typo
 
The Tie-IxHash may USE hashes, but there has to be a lot more to it than that, because it simple is NOT possible to control the order in which either keys or data are retrieved from a hash! Read the man pages and it says so quite clearly. Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Thanks for the information folks. I was running rules on hashed items but found that I could edit that information and print it to my output file without using the hashed data. I simply searched from the value of the hash within the line and edited there before printing. It works quite well. Thanks so much!!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top