Perl: List, Array

By Xah Lee. Date: . Last updated: .

What is Perl List

Perl List roughly means the syntax of sequence of items, before they are assigned to a variable.

What is Perl Array

Perl Array is datatype, it is a sequences of values.

Once a perl list is assigned to a variable, it is an array.

💡 TIP: The term “list” and “array” are often used interchangeably. Does not make much difference.

Create a List

use Data::Dumper;
@aa = (0, 1, 2, 3);
print '@aa is: ', Dumper(\@aa);
# [ 0, 1, 2, 3 ]

Length

To find the number of elements in a list, use scalar.

@xx = (4, 5, 6);
print scalar(@xx), "\n";
# 3

# The + forces a scalar context
print @xx + 0;
# 3

Perl has a “list context” and “scalar context”. How things are evaluated depends on whether the thing is in list or scalar context. “Context” basically means what's adjacent.

When a array is in a scalar context, it returns its length. The function scalar force it into a scalar context.

Add Element

To add a element, or join two lists, use push(array, new_item).

use Data::Dumper;
@xx = (1, 9);
push(@xx, 3);
print Dumper(\@xx);
# [1, 9, 3]
use Data::Dumper;

@aa = (1, 9);
@bb = (3, 4);
@cc = ();

# push elements in lists aa and bb, to cc
push(@cc, @aa, @bb);

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

Get Element

To extract list element, use

@aa = (0, 1, 2, 3, 4);
$cc = @aa[2];
print $cc;
# 2
use utf8;
use Data::Dumper;

@aa = (0, 1, 2, 3, 4, 5, 6, 7);

# get multiple items
@bb = @aa[3, 1, 5];

print Dumper \@bb;
# [3, 1, 5]

Get sublist (slice)

use Data::Dumper;
@xx = (0, 1, 2, 3, 4, 5, 6, 7);
@yy = @xx[1..4];
# the 1..4 creates a range
print Dumper \@yy;
# [1, 2, 3, 4]

Change Element

To replace parts, just assign them. e.g. $myarray[3] = 'rabbit';.

use utf8;
use Data::Dumper;

@xx = (0, 1, 2, 3, 4);
$xx[3] = 99;

print Dumper(\@xx);
# [ 0, 1, 2, 99, 4 ]

Note the dollar sign $ above. This tells Perl that this data is a “scalar”.

Perl, data structure