Perl: Nested List

By Xah Lee. Date: .

Create Nested List

To create a nested list, use square brackets for the inner list.

use Data::Dumper;

@b = (4, 5, [1, 2, [9, 8]], 7);
# nested list

print Dumper \@b;
# [ 4, 5, [ 1, 2, [ 9, 8 ] ], 7 ]

Embed Array into Another

You can embed a array as a nested list into another array. e.g. @b = (4, 5, \@myarray, 7).

use Data::Dumper;

@a=(1, 2, 3);
@b = (4, 5, \@a, 7);  # embed @a as sublist.

print '@b', Dumper \@b;# [ 4, 5, [ 1, 2, 3 ], 7 ]

Get Element in Nested List

To extract element from nested list, use the form $array[index1]->[index2]->[index3]….

use Data::Dumper;

@b = (1, 2, ['x', 'y'], 3);
$c = $b[2]->[1];
print $c;
# 'y'

@b = (1, 2, ['x', [4, 5], 7], 3);
$c = $b[2]->[1]->[1];
print $c;
# 5

Push Flattens List

Perl automatically flatten lists, even if the new item added to list is a list. To force creating a nested list, you have to use square brackets, like this:

use Data::Dumper;

@a = (1, 9);
@b = (5, 6);

# create nested list
push(@a, [@b]);

print Dumper(\@a);  # [1, 9, [3, 4]]

Use Square Brackets to Get Array Reference

Square brackets creates a reference to a array.

use Data::Dumper;

@a = (1, 8);  # array
$b = [1, 8];  # reference to array

print Dumper(\@a);  # [1, 8]
print Dumper($b);   # [1, 8]

Perl, data structure