Is perl's each function worth using?

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

提交回复
热议问题