Vigs Vigs - 1 year ago 50
Perl Question

Get two array values alternately

I'm writing two array contents to file:

@a1 = ('ABC', 'DEF', 'GHI');
@b1 = (1234, 6789, 7635);

open my $fh, ">", "log.txt" or die "Cannot open log.txt: $!";

foreach ( @a1, @a2 ) {
print $fh "$_\n";

close $fh;



I want to write it to the log file in the following manner:

ABC 1234
DEF 6789
GHI 7635

I'm unsure how to achieve it.

Answer Source

You can use the pairwise operator from List::MoreUtils

Like so

use strict;
use warnings 'all';

use List::MoreUtils 'pairwise';

my @a1 = qw/ ABC  DEF  GHI  /;
my @b1 = qw/ 1234 6789 7635 /;

my @pairs = pairwise { [ $a, $b ] } @a1, @b1;

print "@$_\n" for @pairs;


ABC 1234
DEF 6789
GHI 7635

If this ia all you want to do with the pairs then you may avoid the intermediate list altogether and write

pairwise { print "$a $b\n" } @a1, @b1;

with the same result

Note that if one array is shorter than the other then $a or $b will be set to undef after the end of the shorter array. You will have to handle that as appropriate