Search code examples
arraysperl

Merge arrays to make a new array in 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

Solution

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

    or

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