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

前端 未结 19 1641
你的背包
你的背包 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:16

    I came up with this code to solve a similar requirement:

    sub map_pairs(&\@) {
        my $op = shift;
        use vars '@array';
        local *array = shift;    # make alias of calling array
    
        return () unless @array;
    
        # Get package global $a, $b for the calling scope
        my ($caller_a, $caller_b) = do {
            my $pkg = caller();
            no strict 'refs';
            \*{$pkg.'::a'}, \*{$pkg.'::b'};
        };
    
        # Get index counter size.
        my $limit = $#array/2;
    
        # Localize caller's $a and $b
        local(*$caller_a, *$caller_b);
    
        # This map is also the return value
        map {
            # assign to $a, $b as refs to caller's array elements
            (*$caller_a, *$caller_b) = \($array[$_], $array[$_+1]);
            $op->();    # perform the transformation
        } 
        map { 2 * $_ } 0..$limit;  # get indexes to operate upon.
    }
    

    You use it like so:

    @foo = qw( a 1 b 2 c 3 );
    my @bar = map_pairs { "$a is $b" } @foo;
    

    to get:

    @bar = ( 'a is 1', 'b is 2', 'c is 3' );
    

    I've been meaning to submit to the maintainer of List::MoreUtils, but I don't have an XS version to offer.

提交回复
热议问题