Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

syntax for multiple array in a single foreach loop in perl

Tags:

perl

I need to know the proper syntax for multiple arrays in a single foreach loop.

In TCL, we can have multiple list in a single foreach loop. But how to do it with perl?

#TCL eg:
foreach i $a j $e {

}
like image 619
Crazy coder Avatar asked May 31 '26 20:05

Crazy coder


1 Answers

Current versions of the List::MoreUtils module provide a zip_unflatten command which will combine two (or more) arrays into a single array containing references to an array of the first element of each list, then the second, and so on:

#!/usr/bin/env perl    

use strict;
use warnings;
use 5.010;

use List::MoreUtils 'zip_unflatten';

my @a = 1 .. 4;
my @e = 5 .. 9;

my @z = zip_unflatten(@a, @e);

for my $pair (@z) {
  my $i = $pair->[0] // '-';
  my $j = $pair->[1] // '-';

  say "$i\t$j";
}

(The // operator I use here is "defined-OR", which is basically the same as ||, except it works on whether the variable to its left has a defined value rather than whether it has a true value.)

like image 66
Dave Sherohman Avatar answered Jun 04 '26 02:06

Dave Sherohman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!