1

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; 

Output:

ABC
DEF
GHI
1234
6789
7635

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.

1

2 Answers 2

4

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;

output

ABC 1234
DEF 6789
GHI 7635

If this is 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

Sign up to request clarification or add additional context in comments.

Comments

1

Provided that @a1 and @b1 are always the same length:

use strict;
use warnings;

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

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

for my $i (0..$#a1){
    print $fh "$a1[$i] $b1[$i]\n";
}

Or:

use feature qw/ say /;

say $fh join(' ', $a1[$_], $b1[$_]) for 0 .. $#a1;

2 Comments

Tabs are such awful things
Tried this option too and worked fine. Thanks much !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.