Changing keys in a “for ( keys %hash ) {}”-loop

后端 未结 5 446
终归单人心
终归单人心 2021-01-14 08:12

I remember something about not changing the keys in a

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

for example

for my $key ( keys %hash         


        
相关标签:
5条回答
  • 2021-01-14 08:33

    you cannot rename any key value instead you can delete and create a new one which is not lesser than renaming a key! :-)

    for my $key ( keys %hash ) {
        delete $hash{$key}; 
        $hash{$key} = "$key_x";
    }
    
    0 讨论(0)
  • 2021-01-14 08:33

    But , if you want change key name .

    you can delete the keys from hash , then create the key with exist values as you want. this could be a one work around for this requirement

    0 讨论(0)
  • 2021-01-14 08:43

    See the keys function manpage:

    The returned values are copies of the original keys in the hash, so modifying them will not affect the original hash. Compare "values".

    You can delete or change hash elements by subscripting, e.g.

    delete $hash{$key};
    $hash{$key} = "foo";
    
    0 讨论(0)
  • 2021-01-14 08:52

    The way to do this would be

    $hash{$newkey} = delete $hash{$oldkey}; 
    
    0 讨论(0)
  • 2021-01-14 08:59

    I think what you're remembering is the fact that if you do

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

    then adding or removing items in the middle of @array (for instance by using splice) is disallowed, and the result if you try it is undefined. In fact, in olden days you could actually crash perl that way.

    Since the list returned by keys is a copy, it's determined entirely at the moment the loop starts, and adding and removing keys from the hash won't affect the loop at all. That means that you can do things like

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

    100% safely without worrying. I can promise this is true back to perl 5.6.1 (April 2001), which was when the note that "the returned values are copies" was added to perlfunc, but it seems that it's been so since forever, and the change was only to the docs.

    Since $key in the loop is aliased to a value in a temporary list, you can change it without anything bad happening, but it won't have any effect on %hash at all.

    0 讨论(0)
提交回复
热议问题