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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With