更改“for(keys%hash){}”-loop中的键 [英] Changing keys in a "for ( keys %hash ) {}"-loop
问题描述
我记得一些关于不改变我的$ key(键%hash){...
中的键的信息。
例如
给我的$ key(键%hash){
$ key =$ key_x;
}
但是删除键和更改值会很好。
我的回忆可以吗?
我想你记得的事实是,如果你这样做的话
$ b $为我的$ item(@array){
...
}
$ p $ 然后在
@array
的中间添加或删除项目(例如,通过使用 splice $ b $ p> / code>)是不允许的,如果你尝试这个结果是未定义的。事实上,在过去的几天里,你可能会以这种方式崩溃perl。
由于 keys
返回的列表是复制,这完全是在循环开始的时刻完成的,添加和删除哈希键不会影响循环。这意味着你可以为我的$ key(键%hash){
$ hash {lc)做类似于
$ key} =删除$ hash {$ key};
}
100%安全无忧。我可以承诺,这是真实的回到perl 5.6.1(2001年4月),这是当返回的值是副本的注释被添加到perlfunc,但它似乎永远是这样,只是变化是由于 $ key
在循环中被别名化为一个临时列表中的一个值,所以你可以改变它没有什么不好的事情发生,但它不会对%hash
有任何影响。
I remember something about not changing the keys in a
for my $key ( keys %hash ) { ...
for example
for my $key ( keys %hash ) {
$key = "$key_x";
}
But deleting keys and changing values would be fine. Are my memories OK?
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.
这篇关于更改“for(keys%hash){}”-loop中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!