Arrays

An array is a variable that stores an ordered list of scalar values. Arrays are preceded by an “at” sign (@).

@numbers = (1,2,3);        # Set the array @numbers to (1,2,3)

To refer to a single element of an array, use the dollar sign ($) with the variable name (it’s a scalar), followed by the index of the element in square brackets (the subscript operator). Array elements are numbered starting at 0. Negative indexes count backwards from the last element in the list (i.e., -1 refers to the last element of the list). For example, in this list:

@date = (8, 24, 70);

$date[2] is the value of the third element, 70.

Get Perl in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.