Reputation: 135397
I understand that a hash is not ordered in perl. What I am concerned about is if I can depend on the keys and values coming out with an index relationship.
Say I have this hash
my %h = ("a" => 1, "b" => 2, "c" => 3, "d" => 4);
If I do keys %h
, I might get
("b", "a", "d", "c")
Would I be guaranteed that values %h
would come out in the same order to match keys? Can I expect?
(2, 1, 4, 3)
Or is there no guarantee that there's any index relationship between keys %h
and values %h
?
Upvotes: 4
Views: 870
Reputation: 163
Although the order that keys and values return their contents can vary according to machine and implementation, you can count on the fact that they will both produce the same order. Alternatively, you can use the function "each" to pull both keys and values at the same time:
while (($key,$value) = each %ENV) {
print "$key=$value\n";
}
The advantage of using each is that perl won't have to allocate enough memory for all the keys and values at once, so it will be more efficient if you are iterating through a large hash.
Upvotes: 3
Reputation: 57640
Yes. As long as the hash is not changed (insertion or deletion), keys
, values
and each
will keep the same order:
So long as a given hash is unmodified you may rely on keys, values and each to repeatedly return the same order as each other.
– from
perldoc -f keys
So you could safely copy a hash like:
my %orig = ...;
my %copy;
@copy{keys %orig} = values %orig;
Upvotes: 11