Merge arrays to make a new array in perl
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]);
}
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];
}
my @merged;
for (0 .. $#array1) {
push(@merged, ([$array1[$_],$array2[$_]]));
}
or
my @merged;
push @merged, map {[$array1[$_], $array2[$_]]} 0 .. $#array1;
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.