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?
As of Ruby 1.9, hashes also maintain order, but usually ordered items are stored in an array.
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.
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
oreach
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" inperldoc perlsec
).
(emphasis mine)
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