Vijay
Vijay

Reputation: 67319

Join elements of two arrays and create a result array in perl

Basically what i need if i have two arrays like below:

my @a=("a","b","c");
my @z=("x","y","z");

I want the result array to be:

("a x","b y","c z")

pre condition is the number is elements in both the array are always same. post condtion is the order should be same as the original array order. i have written a simple loop

my $i;
for($i=0;$i<scalar(@a);$i++)
{
push(@result,$a[$i]." ".$z[$i]);
}

And the above works. But is there any better way of doing this?

Upvotes: 3

Views: 174

Answers (2)

DJG
DJG

Reputation: 6563

Inspired by an answer to this question. You can use each_array from List::MoreUtils to make it a little cleaner to iterate over two arrays at a time.

#!/usr/bin/perl
use warnings;
use strict;

use List::MoreUtils qw/each_array/;

my @a = qw/a b c/;
my @b = qw/x y z/;
my $it = each_array(@a, @b);

my @result;

while (my ($x, $y) = $it->()) {
        push @result, $x . " " . $y;
}

Upvotes: 3

choroba
choroba

Reputation: 242383

You can use map, which is a loop in disguise:

my @result = map "$a[$_] $z[$_]", 0 .. $#a;

Upvotes: 6

Related Questions