Is perl's each function worth using?

后端 未结 8 1803
忘掉有多难
忘掉有多难 2021-01-17 11:37

From perldoc -f each we read:

There is a single iterator for each hash, shared by all each, keys, and values

8条回答
  •  遇见更好的自我
    2021-01-17 12:27

    each is too dangerous to ever use, and many style guides prohibit its use completely. The danger is that if a cycle of each is aborted before the end of the hash, the next cycle will start there. This can cause very hard-to-reproduce bugs; the behavior of one part of the program will depend on a completely unrelated other part of the program. You might use each right, but what about every module ever written that might use your hash (or hashref; it's the same)?

    keys and values are always safe, so just use those. keys makes it easier to traverse the hash in deterministic order, anyway, which is almost always more useful. (for my $key (sort keys %hash) { ... })

提交回复
热议问题