Chapter 2. All About Arrays
Nathan Torkington
Arrays are one of Perl’s three primary data types (the other two are scalars and hashes). This article will help you understand everything that can be done with them.
Basics
All array variables begin with an @ sign. They hold a list of scalar values (such as a string or number) whose positions are numbered beginning from 0. So in this code, blue
is in position number 2 of the @colors
array, and 42
is in position 3 of the @data
array:
@colors = ("red", "green", "blue")
@data = ("Perl", 2_000_000, "Wall", 42);
At this early point it’s good to start distinguishing lists from arrays. Perl gurus try to be precise about this distinction when they talk about their code: both are sequences of scalars, but while arrays are true stored variables, lists are merely temporary sequences of values. Subroutines accept lists, and can return them; as you pass an array into a subroutine, it becomes a list of values. Likewise, when a subroutine returns a list, you can store it in an array.
You store a list inside an array variable if you want to access the list’s values later. Subroutines and functions don’t, strictly speaking, accept arrays, except for a few special functions that we’ll see later. Where Perl expects a bunch of values to work on, those values can come from a list, whether it’s hardcoded in the program, returned by a function, or extracted from an array.
Inside double-quoted strings, arrays interpolate (expand) into their values, separated by ...
Get Computer Science & Perl Programming 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.