Will keys and values of a hash have the same “order” in Perl?

倾然丶 夕夏残阳落幕 提交于 2020-01-13 11:28:18

问题


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?


回答1:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/23092872/will-keys-and-values-of-a-hash-have-the-same-order-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!