Can I copy a hash without resetting its “each” iterator?

后端 未结 4 461
广开言路
广开言路 2020-12-07 00:59

I am using each to iterate through a Perl hash:

while (my ($key,$val) = each %hash) {
   ...
}

Then something interesting happ

4条回答
  •  余生分开走
    2020-12-07 01:22

    Not really. each is incredibly fragile. It stores iteration state on the iterated hash itself, state which is reused by other parts of perl when they need it. Far safer is to forget that it exists, and always iterate your own list from the result of keys %hash instead, because the iteration state over a list is stored lexically as part of the for loop itself, so is immune from corruption by other things.

提交回复
热议问题