How do I read two items at a time in a Perl foreach loop?

前端 未结 19 1632
你的背包
你的背包 2020-12-14 15:12

What I\'m looking for is something like:

@list = qw(1 2 3 4 5 6);
foreach (@list) {
  #perl magic goes here 
  print \"i: $i, j:$j\\n\";
}

19条回答
  •  时光取名叫无心
    2020-12-14 15:42

    If I only could use standard Perl with no modules, I'd probably drop down to a C-style for loop that counts by 2:

    for( my $i = 0; $i < @array; $i += 2 ) {
        my( $j, $k ) = @array[ $i, $i+1 ];
        ...
        }
    

    If you have an odd number of elements, you'll have to decide how to handle an extra element. Your problem may not care that you get an extra element that is undefined since you specifically need pairs.

    Simply reading past the end of an array does not change the array, so that part is fine.

    If you must have pairs, a simple tactic might be to add an appropriate value to the end of the array so you always end up with pairs. Likewise, you can remove the last element (or whichever element) to end up with an even number again. Those depend on your problem.

    Otherwise, you're doing slightly more work:

    for( my $i = 0; $i < @array; $i += 2 ) {
        push @pair, $array[$i];
        push @pair, $array[$i+1] if $i+1 <= $#array;
        ... 
        }
    

    However, if you wanted something fancy from one of the modules you can't use, you can just add that module to your code. If you can write code, you can use modules. You might just have to include the module with all of the code you deliver while you set @INC appropriately. This is the basic idea of inc::Module::Install and PAR.

    I spend a lot of my time working with a build system that creates its own CPAN repository, installs its dependencies from its private CPAN, and then tests code. Having a build farm doesn't preclude using modules; it's local policy that does. However, that might not make sense in all cases even though it's possible.

提交回复
热议问题