3.4. Array Operators and Functions

Array functions and operators act on entire arrays. Some return a list, which can then either be used as a value for another array function, or assigned into an array variable.

3.4.1. Assignment

Probably the most important array operator is the array assignment operator, which gives an array variable a value. It is an equal sign, just like the scalar assignment operator. Perl determines whether the assignment is a scalar assignment or an array assignment by noticing whether the assignment is to a scalar or an array variable. For example:

@fred = (1,2,3); # The fred array gets a three-element literal
@barney = @fred; # now that is copied to @barney

If a scalar value is assigned to an array variable, the scalar value becomes the single element of an array:

@huh = 1; # 1 is promoted to the list (1) automatically

Array variable names may appear in a list literal list. When the value of the list is computed, Perl replaces the names with the current values of the array, like so:

@fred = qw(one two);
@barney = (4,5,@fred,6,7); # @barney becomes 
                           # (4,5,"one","two",6,7)
@barney = (8,@barney);     # puts 8 in front of @barney
@barney = (@barney,"last");# and a "last" at the end
                        # @barney is now (8,4,5,"one","two",6,7,"last")

Note that the inserted array elements are at the same level as the rest of the literal: a list cannot contain another list as an element.[2]

[2] Although a list reference is permitted as a list element, it's not really a list as a ...

Get Learning Perl, Second 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.