Is it possible to assign two variables in Perl foreach loop?

后端 未结 4 2282
旧时难觅i
旧时难觅i 2021-02-19 00:40

Is it possible to assign two variables the same data from an array in a Perl foreach loop?

I am using Perl 5, I think I came across something in Perl 6.

Somethi

4条回答
  •  孤街浪徒
    2021-02-19 01:28

    It's not in the Perl 5 core language, but List::Util has a pairs function which should be close enough (and a number of other pair... functions which may be more convenient, depending on what you're doing inside the loop):

    #!/usr/bin/env perl    
    
    use strict;
    use warnings;
    use 5.010;
    
    use List::Util 'pairs';
    
    my @list = qw(a 1 b 2 c 3);
    
    for my $pair (pairs @list) {
      my ($first, $second) = @$pair;
      say "$first => $second";
    }
    

    Output:

    a => 1
    b => 2
    c => 3
    

提交回复
热议问题