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
?
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;
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