Changing keys in "for (keys% hash)" {} "- loop

I remember something about not changing keys in

for my $key ( keys %hash ) { ...

eg

for my $key ( keys %hash ) {
    $key = "$key_x";
}

But deleting keys and changing values ​​will be wonderful. Are my memories okay?

+3
source share
5 answers

I think you remember the fact that if you do

for my $item (@array) {
    ...
}

then adding or removing elements in the middle @array(for example, using splice) is not allowed, and the result, if you try, is undefined. In fact, in the old days, you could actually bring down perl this way.

, keys, , , . , ,

for my $key (keys %hash) {
    $hash{lc $key} = delete $hash{$key};
}

100% , . , , perl 5.6.1 ( 2001 .), ​​ , " " perlfunc, , , .

$key , - , %hash.

+12

. keys manpage:

- , . "".

, .

delete $hash{$key};
$hash{$key} = "foo";
+5

The way to do it would be

$hash{$newkey} = delete $hash{$oldkey}; 
+4
source

you cannot rename any key value, instead you can delete and create a new one which is no less than renaming the key !:-)

for my $key ( keys %hash ) {
    delete $hash{$key}; 
    $hash{$key} = "$key_x";
}
+1
source

But, if you want to change the key name.

you can remove the keys from the hash, then create a key with existing values ​​as you wish. it could be one job around this requirement

0
source

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


All Articles