Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one print the elements of a hash in the order they were added to the hash

Tags:

hash

perl

How does one print the key/value pairs of a hash in the order they were added to the hash.

For example:

%hash = ("a", "1", "b", "2", "c", "3");
while (($key, $value) = each %hash) {
   print "$key", "$value\n";
}

The above results in the following:

c3
a1
b2

I am looking for a way to print the following:

a1
b2
c3

Thanks in advance!

like image 413
Jack Pettersson Avatar asked Nov 27 '22 17:11

Jack Pettersson


1 Answers

How do you print the key/value pairs of a hash, in the order they appear in the hash.

The code you used does exactly that. c3, a1, b2 is the order in which the elements appear in the hash at that time.

What you actually want to do with print them in the order they were inserted. For that, you'll need to keep track of the order in which elements were inserted, or you'll have to use something other than a hash, such as aformentioned Tie::IxHash and Tie::Hash::Indexed.

like image 117
ikegami Avatar answered Dec 10 '22 03:12

ikegami