Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 43 ยท Arrays and Hashes

Arrays

Learn Perl arrays: creating lists with qw, zero-based and negative indexing, $#array, push, pop, shift, unshift, splice, slices and looping with foreach.

An array is an ordered list of scalars. It is Perl's workhorse for anything that has a sequence: lines of a file, command-line arguments, search results, the fields of a record. Arrays grow and shrink on demand, they can hold numbers, strings and even a mix of both, and Perl gives you a generous set of built-in operators to add, remove, slice and loop over their elements.

Array variables start with the @ sigil. When you pick out a single element, the sigil changes to $, because that one element is a scalar. This is the first oddity to learn, and the lesson explains why it makes sense. If context is still new to you, skim Context: Scalar vs List first, because arrays behave differently in scalar and list context.

Perl is not installed on this site, so the Perl listings are read-only; their outputs come from real runs of Perl 5.42. The TryIt blocks use Python lists as a stand-in so you can experiment with the same ideas.

Creating arrays

You fill an array with a comma-separated list in parentheses. The qw operator ("quote words") saves typing when the elements are simple words, because it splits on whitespace and needs no quotes or commas:

PERL
use v5.36;

my @colors = ("red", "green", "blue");
my @words  = qw(alpha beta gamma delta);
my @empty  = ();
my @mixed  = (42, "text", 3.14);

Arrays are flat. Putting one array inside another list flattens it, so (@a, @b) is one long list. To nest structures you need references, covered in References.

Indexing

Indexes start at zero. Because a single element is a scalar, you write $colors[0] with a dollar sign, not @colors[0]. Negative indexes count from the end:

PERL
say $colors[0];        # red
say $colors[-1];       # blue
say $colors[$#colors]; # blue
say scalar(@colors);   # 3   (the size)
say $#colors;          # 2   (the index of the last element)

$#colors is the last valid index, always one less than the size. Assigning to it resizes the array: $#colors = 1; throws away everything after index 1, and $#colors = -1; empties it.

Perl never complains about an out-of-range index when you read; you just get undef (and a warning under use warnings). Writing past the end extends the array and fills the gap with undef:

PERL
$colors[5] = "pink";
say scalar(@colors);   # 6
# colors is now: red, green, blue, undef, undef, pink

Use exists $colors[3] to test whether an element has been stored at all, and defined $colors[3] to test that its value is not undef.

Four ways to change the ends

unshift Add to the front.
push Add to the back.
shift Remove from the front.
pop Remove from the back.

push and pop make a stack; push and shift make a queue.

1 / 2

push, pop, shift and unshift

These four functions work at the ends of an array and are the everyday way to grow and shrink it:

PERL
my @stack = ("red", "green", "blue");

push @stack, "yellow", "black";   # red green blue yellow black
my $last = pop @stack;            # "black"
my $first = shift @stack;         # "red"
unshift @stack, "white", "gray";  # white gray green blue yellow

push and unshift accept any number of values and return the new size. pop and shift return the removed element, or undef if the array is empty. Remember shift has another job: inside a subroutine, a bare shift removes the first argument. You will meet that in Subroutines.

Python Changing the ends of an array (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

splice

splice removes, inserts or replaces elements anywhere in an array. It takes the array, an offset, an optional length and an optional replacement list, and returns the removed elements:

PERL
my @n = (10 .. 20);
my @removed = splice(@n, 2, 3);       # removes 12 13 14
# @removed = (12, 13, 14)
# @n       = (10, 11, 15, 16, 17, 18, 19, 20)

splice(@n, 1, 0, 99, 98);             # insert before index 1, remove nothing
# @n = (10, 99, 98, 11, 15, ... 20)

splice(@n, -2);                       # remove the last two elements
splice(@n, 1, 2, "x");                # replace two elements with one
# @n = (10, "x", 11, 15, 16, 17, 18)

A length of 0 inserts, a replacement list shorter or longer than the length changes the array size, and a negative offset counts from the end. If you leave out the length, splice removes everything from the offset to the end.

Slices

A slice picks several elements at once. It uses the @ sigil with a list of indexes, because the result is a list:

PERL
my @w = qw(a b c d e f);
say "@w[1,2]";      # b c
say "@w[1..3]";     # b c d
say "@w[-2,-1]";    # e f

Slices also work on the left-hand side of an assignment, which makes swaps tidy:

PERL
my ($x, $y) = (1, 2);
($x, $y) = ($y, $x);     # swap, no temporary variable
@w[0, 1] = @w[1, 0];     # now: b a c d e f
my ($head, @tail) = @w;  # $head = "b", @tail = the rest

Notice that @w[1,2] and $w[1] use different sigils for different things: @ for "a list of elements", $ for "one element". The same pattern applies to hashes in Hashes.

Python Slices and splice (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Looping over an array

foreach (also spelled for) visits each element. The loop variable is an alias for the real element, not a copy, so changing it changes the array:

PERL
foreach my $c (@words) {
    print uc($c), " ";
}
print "\n";                  # ALPHA BETA GAMMA DELTA

my @nums = (1, 2, 3);
$_ *= 2 for @nums;           # @nums is now (2, 4, 6)

When you need the index as well, loop over the index range with 0 .. $#array:

PERL
for my $i (0 .. $#words) {
    say "$i: $words[$i]";
}

Perl 5.40 and later can also give you index and value together with foreach my ($i, $c) (builtin::indexed @words). Loops are covered fully in Loops and Loop Control.

Copying, joining and testing

Assigning an array copies it. The copy is independent, so changing one does not change the other:

PERL
my @copy = @nums;
push @copy, 99;
say "@nums | @copy";   # 2 4 6 | 2 4 6 99
my @both = (@nums, @copy);   # flatten two arrays into one

Some useful companions:

  • join(", ", @words) builds a string, and split goes the other way.
  • reverse @words returns the reversed list.
  • sort @words returns a sorted copy (see List Functions and Sorting).
  • An empty array is false, so say "empty" unless @list; works.
  • Inside double quotes, "@words" interpolates the elements separated by spaces, and the separator is controlled by the special variable $". A literal at-sign in a string must be escaped: "email\@example.com".

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given my @a = qw(x y z);, what are $a[-1] and $#a?

    A negative index counts from the end, so $a[-1] is "z". $#a is the last valid index, which is 2 for three elements.
  2. 2. Why do we write $colors[0] instead of @colors[0] to read one element?

    The sigil shows the type of the result. One element is a scalar ($), while a slice such as @colors[0,1] is a list (@).
  3. 3. What does splice(@n, 1, 0, 99) do?

    The length 0 means no elements are removed, so the replacement list is inserted at the given offset.
  4. 4. After my @n = (1, 2, 3); $_ *= 10 for @n; what is in @n?

    The loop variable aliases each element, so assigning to it changes the array itself.
  5. 5. What does $colors[5] = "pink"; do to an array with three elements?

    Perl arrays grow automatically. Indexes 3 and 4 become undef.

Summary

  • Arrays use the @ sigil; a single element is $a[0] and a slice is @a[1,2].
  • Indexes start at 0, negative ones count from the end, $#a is the last index and scalar(@a) the size.
  • push/pop work at the end, unshift/shift at the start, and splice anywhere.
  • foreach aliases each element, so assigning to the loop variable changes the array.
  • Reading past the end gives undef; writing past the end extends the array.

Next: List Functions and Sorting