Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Perl guaranteed to return consistently-ordered hash keys?

Tags:

key

hash

perl

Given something like

foreach (keys %myHash) {
   ... do stuff ...
}

foreach (keys %myHash) {
   ... do more stuff ...
}

Is Perl guaranteed to iterate over the keys in a consistent order if the hash is not altered?

like image 924
erjiang Avatar asked Aug 10 '09 18:08

erjiang


People also ask

Does hashing maintain key order?

As of Ruby 1.9, hashes also maintain order, but usually ordered items are stored in an array.

What does keys do in Perl?

keys() function in Perl returns all the keys of the HASH as a list. Order of elements in the List need not to be same always, but, it matches to the order returned by values and each function. Return: For scalar context, it returns the number of keys in the hash whereas for List context it returns a list of keys.


1 Answers

Yes. From perldoc -f keys:

The keys are returned in an apparently random order. The actual random order is subject to change in future versions of perl, but it is guaranteed to be the same order as either the values or each function produces (given that the hash has not been modified). Since Perl 5.8.1 the ordering is different even between different runs of Perl for security reasons (see "Algorithmic Complexity Attacks" in perldoc perlsec).

(emphasis mine)

like image 76
Adam Batkin Avatar answered Oct 21 '22 13:10

Adam Batkin