Perl: List, Array

By Xah Lee. Date: . Last updated: .

What is List, Array

The words list and array are often used interchangeably.

but technically:

now, Perl Array:

Create a List

@a = (0, 1, 2, 'three', 4, 5, 6, 7);
# assigns a list to @a.

use Data::Dumper;   # loads the list-printing module

print '@a is:', Dumper(\@a);

Length

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

@a = (4, 5, 6);   # a list

print scalar(@a);
# prints 3. The length.

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

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;

@b = (1, 9);
push(@b, 3);  # add a element to @b, at the end

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

@a = (1, 9);
@b = (3, 4);
@c = ();

push(@c, @a, @b);   # @c is the joined list of @a and @b

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

Get Element

To extract list element, use

@a = (0, 1, 2, 3, 4);
$c = @a[2];

print $c;
# 2
use utf8;
use Data::Dumper;

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

# get multiple items
@b = @a[3, 1, 5];

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

Get sublist (slice)

use Data::Dumper;

@a = (0, 1, 2, 'three', 4, 5, 6, 7);
@b = @a[1..4];  # the 1..4 creates a range

print Dumper \@b;   # [1, 2, 'three', 4]

Change Element

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

use utf8;
use Data::Dumper;

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

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

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

Perl, data structure