Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge arrays to make a new array in perl

Tags:

arrays

perl

What is the way to merge two arrays (column-wise) into a new composite array in perl?

@array1

car
scooter
truck

@array2

four
two
six

I tried using following:

my @merged = (@array1, @array2); print @merged;

But it merges both arrays in one column as follows:

car
scooter
truck
four
two
six

But what I want is as follows:

@merged[0] @merged[1] 
car             four
scooter         two
truck           six
like image 871
Vinay Avatar asked Feb 22 '18 06:02

Vinay


4 Answers

my @merged;
for (0 .. $#array1) {
    push(@merged, ([$array1[$_],$array2[$_]]));
}

or

my @merged;
push @merged, map {[$array1[$_], $array2[$_]]} 0 .. $#array1;
like image 129
Scott Pritchett Avatar answered Sep 19 '22 06:09

Scott Pritchett


In Perl, if you are storing the array(s) in list it will automatically flattened as a single list.

my @array = (@ar1,@ar2);

If you want to store as an array, you should make a reference to an array and store the reference to another array like

my @array = (\@ar1,\@ar2);

Now @array has reference of @ar1 and @ar2.

Then use corresponding datatype to dereference the reference

In your case

print @{$array[0]}; 

Finally you can use the following for your case

use warnings;
use strict;

my @array1 = qw(car scooter truck);
my @array2 = qw(four five six);

my @merged = (\@array1,\@array2); #referencing the array1 and array2

foreach my $i (0..$#{$merged[0]}) 
{
    # getting the last index value using $#{$merged[0]}

    printf ("%-10s%-10s\n",$merged[0][$i],$merged[1][$i]);


}
like image 26
mkHun Avatar answered Sep 19 '22 06:09

mkHun


This will do as requested:

my @merged;
for (my $i=0; $i<=$#array1; ++$i)
{
    $merged[$i*2] = $array1[$i];
    $merged[$i*2+1] = $array2[$i];
}
like image 36
Edward Kirton Avatar answered Sep 18 '22 06:09

Edward Kirton


But what I want is as follows:

@merged[0] @merged[1] 
car             four
scooter         two
truck           six

I see two ways to interpret this.

Either as mkHun did, as a list of two array references:

my @array1 = qw(a b c);
my @array2 = qw(x y z);
my @merged = (\@array1, \@array2); # (['a', 'b', 'c'], ['x', 'y', 'z'])

at which point you can do:

$merged[0]->[1] # 'b'
$merged[1]->[2] # 'z'

Or as a single list of interleaved elements:

use List::MoreUtils qw(zip);

my @array1 = qw(a b c);
my @array2 = qw(x y z);
my @merged = zip @array1, @array2; # ('a', 'x', 'b', 'y', 'c', 'z')

at which point you can do:

$merged[2] # 'b'
$merged[5] # 'z'

See List::MoreUtils::zip for this.

like image 27
sshine Avatar answered Sep 21 '22 06:09

sshine