Best way to iterate through a Perl array

后端 未结 6 1233
死守一世寂寞
死守一世寂寞 2020-12-23 03:03

Which is the best implementation(in terms of speed and memory usage) for iterating through a Perl array? Is there any better way? (@Array need not be retained).

6条回答
  •  鱼传尺愫
    2020-12-23 03:06

    If you only care about the elements of @Array, use:

    for my $el (@Array) {
    # ...
    }
    

    or

    If the indices matter, use:

    for my $i (0 .. $#Array) {
    # ...
    }
    

    Or, as of perl 5.12.1, you can use:

    while (my ($i, $el) = each @Array) {
    # ...
    }
    

    If you need both the element and its index in the body of the loop, I would expect using each to be the fastest, but then you'll be giving up compatibility with pre-5.12.1 perls.

    Some other pattern than these might be appropriate under certain circumstances.

提交回复
热议问题