Perl: List/Array Tutorial

By Xah Lee. Date: . Last updated: .

List Construction

In Perl, a list is created by enclosing elements in the parenthesis “()”. To assign a list to a variable, the variable must have a “@” sign in front. To print a list, use the “Dumper” function in the package “Data::Dumper”. Example:

# -*- coding: utf-8 -*-
# perl

@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);

The backslash in front of @a is necessary. It returns the “reference” of the array @a, and the argument to Dumper must be a reference. Once a list is assigned to a variable, it's called array. For detail, see: Perl: Difference Between List and Array.

Counting Elements

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

# -*- coding: utf-8 -*-
# perl

@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 list/array is in a scalar context, it returns its length. The function scalar forces things in a scalar context.

Adding Elements

To add a element, or join two lists, use “push”.

# -*- coding: utf-8 -*-
# perl

use Data::Dumper;

# append to a list

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

print Dumper(\@b);  # [1, 9, 3]
# -*- coding: utf-8 -*-
# perl

use Data::Dumper;

# join lists

@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]

Perl automatically flatten array/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:

# -*- coding: utf-8 -*-
# perl

use Data::Dumper;

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

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

print Dumper(\@a);  # [1, 9, [5, 6]]

Technically, the backslash forces the list into a reference.

Getting Elements

To extract list element, use @array[index]. The index can be several integers separated by comma, for getting multiple elements.

# -*- coding: utf-8 -*-
# perl

use Data::Dumper;

@a = (0, 1, 2, 'three', 4, 5, 6, 7);
@b = @a[3, 1, 5]; # ['three', 1, 5]
$c = @a[2];   # gets 2

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

print $c, "\n";   # 2

Changing Elements

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

# -*- coding: utf-8 -*-
# perl

use Data::Dumper;

@a = (0, 1, 2, 'three', 4);
$a[3] = 'new';

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

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

In Perl, a variable of “scalar” type (such as numbers and strings) starts with a $. A variable for array (aka list) starts with the sign @. A variable for harshes/dictionaries starts with %. All Perl variables must start with one of {$ @ %}. (this is a simplified story)

Nested List

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

# -*- coding: utf-8 -*-
# perl

use Data::Dumper;

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

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

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

# -*- coding: utf-8 -*-
# perl

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 ]

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

# -*- coding: utf-8 -*-
# perl

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

perldoc perldata

See also: Perl: Difference Between List and Array

If you have a question, put $5 at patreon and message me.

Perl

  1. Perl Overview
  2. Version String
  3. Help System

Detail

  1. Quoting String
  2. Format String
  3. String Operations
  4. True, False
  5. if then else
  6. Loop
  7. List / Array
  8. Loop Thru List
  9. Map f to List
  10. List Comprehension
  11. Hash Table
  12. Function Optional Param
  13. regex

Text Processing

  1. Unicode 🐪
  2. Convert File Encoding
  3. Read Write File
  4. Traverse Dir
  5. Find Replace
  6. Validate Local Links
  7. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. Sort Unstable
  4. Sort Misc
  5. List Modules, Search Paths
  6. Write a Module
  7. Complex Numbers
  8. System Call
  9. gzip
  10. Get Env Var
  11. GET Web Content
  12. Email