0

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?

2
  • Using splice you can do this operation. Commented Jun 10, 2020 at 15:08
  • See perldsc with the help of tutorial perlreftut, backed by reference perlref Commented Jun 11, 2020 at 5:19

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

What do you mean Perl doesn't have nested array? it's absolutely wrong, Perl supports multi-dimensional arrays well.
The way this is implemented is using array references. See for instance here: geeksforgeeks.org/perl-multidimensional-arrays
1

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]

3 Comments

splice doesn't return the modified array. splice modifies the array in place and returns the removed elements (or the last removed element in scalar context).
if I don't want to create a new array instead I want to update the array1 itself can I simply do splice @array1, 2, 0, @data? Will it update?
It might be better to remove the [] characters, since those have meaning in Perl. Or use some other characters. I'm also not sure if this actually answers OP's question, since they want a nested array, and I believe this won't nest the replacement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.