Biswajit Maharana
Biswajit Maharana

Reputation: 609

How to insert an array into another array at a particular index in perl

I'm very new to perl. Need some assistance in the below scenario.

I have declared an array and trying to initialize like

my @array1;
$array1[0] = 1;
$array1[1] = 2;
$array1[3] = 4;

Now I want to insert another array lets say my @data = [10,20,30]; at index 2 of array1.

So after insert array1 should look like [1, 2, [10,20,30],4]

How can I do that?

Upvotes: 0

Views: 1378

Answers (3)

gmatht
gmatht

Reputation: 835

You will need to use array references.

In short you can do

$array1[2] = \@data;

This will make the second member of $array1 a reference to @data. Because this is a reference you can't access it in quite the same way as a normal array. To access @data via array1 you would use @{$array1[2]}. To access a particular member of the reference to @data you can use -> notation. See for example the simple program below:

use strict;
use warnings;

my @array1;

$array1[0] = 1;
$array1[1] = 2;
$array1[3] = 4;
my @data = (10,20,30);
$array1[2] = \@data;

print "A @array1\n";   #Note that this does not print contents of data @data
print "B @{$array1[2]}\n"; #Prints @data via array1
print "C $array1[2]->[0]\n"; #Prints 0th element of @data

Upvotes: 2

Mahdi Zarei
Mahdi Zarei

Reputation: 221

You can use splice for doing so.

use Data::Dumper;
splice @array1, 2, 0, @data;
print Dumper \@array1;

the splice prototype is:

splice [origin array], [index], [length of elements to replace], [replacement]

Upvotes: 1

Hellmar Becker
Hellmar Becker

Reputation: 2972

You can write

$array1[2] = [10,20,30];

Be aware that what you inserting into the host array is actually an array reference. Hence the syntax: [10,20,30] is a reference while (10,20,30) is a list proper.

Perl doesn't have nested arrays.

Upvotes: 1

Related Questions