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?
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?
Edit:
Although a normal hash has a consistent ordering, in the case of a tied hash the order of the keys is not well defined, as it is user-controlled!
Although the hash key order does not change, you probably should reconsider why you need to do this.
Perhaps you can process the hash in one pass instead of two?
You should save the hash keys into an array as a defensive programming practice, unless the size of the data is large enough that duplicating it would be a problem. As a bonus, you can even sort the list easily and process in the hash in a well defined order. E.g.,
This avoids any problems with modifying the hash, since your array order will never change unless you want it to.
If you do not do this, you need to be very careful not to do anything that changes the hash, otherwise the order of the elements will change. Look into the Readonly module to ensure that this hash is never modified.
Yes. From
perldoc -f keys
:(emphasis mine)
This is a pretty dicey expectation. It probably will, but why worry? Fetch keys in advance, save the result, then iterate over the saved result. Then, you're guaranteed to access keys in same order. Working around the edges of unspecified implementation details is dangerous.
EDIT: Missed the "guarantee" in the doc, but I still think it's dangerous to expect this will never change. Especially when there are saner ways to achieve the same ends.