Is perl's each function worth using?

后端 未结 8 1669
忘掉有多难
忘掉有多难 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

    I find each to be very handy for idioms like this:

    my $hashref = some_really_complicated_method_that_builds_a_large_and_deep_structure();
    while (my ($key, $value) = each %$hashref)
    {
        # code that does stuff with both $key and $value
    }
    

    Contrast that code to this:

    my $hashref = ...same call as above
    foreach my $key (keys %$hashref)
    {
        my $value = $hashref->{$key};
        # more code here...
    }
    

    In the first case, both $key and $value are immediately available to the body of the loop. In the second case, $value must be fetched first. Additionally, the list of keys of $hashref may be really huge, which takes up memory. This is occasionally an issue. each does not incur such overhead.

    However, the drawbacks of each are not instantly apparent: if aborting from the loop early, the hash's iterator is not reset. Additionally (and I find this one more serious and even less visible): you cannot call keys(), values() or another each() from within this loop. To do so would reset the iterator, and you would lose your place in the while loop. The while loop would continue forever, which is definitely a serious bug.

    0 讨论(0)
  • 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) { ... })

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