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

I understand that the hash is not ordered in perl. It bothers me if I can depend on the keys and values ​​that occur with the index relation.

Say I have this hash

my %h = ("a" => 1, "b" => 2, "c" => 3, "d" => 4);

If I do keys %h, I can get

("b", "a", "d", "c")

Will it be guaranteed to values %hcome out in the same order to match the keys? Can i expect

(2, 1, 4, 3)

Or is there no guarantee that there is any index relation between keys %hand values %h?

+4
source share
2 answers

Yes. While the hash does not change (insertion or deletion) keys, valuesand eachwill maintain the same procedure:

, , , .

- perldoc -f keys

, , :

my %orig = ...;
my %copy;
@copy{keys %orig} = values %orig;
+11

, , , , . , "", :

while (($key,$value) = each %ENV) {
    print "$key=$value\n";
}

, perl , .

+3

Source: https://habr.com/ru/post/1536659/


All Articles