Is perl's each function worth using?

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

    I think it is worth using as long as you are aware of this. It's ideal when you need both key and value in iteration:

    while (my ($k,$v) = each %h) {
        say "$k = $v";
    }
    

    In your example you can reset the iterator by adding keys %h; like so:

    my %h = map { $_ => 1 } qw/1 2 3/;
    while (my $k = each %h) { print "1: $k\n"; last }
    keys %h;  # reset %h
    while (my $k = each %h) { print "2: $k\n" }
    

    From Perl 5.12 each will also allow iteration on an array.

提交回复
热议问题