3.1.11 Using an Array Literal on the Left Hand Side of an Assignment

It is possible to use an array literal on the left hand side of an assignment. In such a case, the array literal must be composed of all variables, whether scalars or arrays. Using undef is acceptable in place of a scalar variable.

Assuming @friends has been assigned a value (it is alright even if it is unassigned and is empty), we can write the following.

($firstFriend, $secondFriend, @restFriends) = @friends;

The assignment statement will cause the two scalars $firstFriend, $secondFriend and the array

@restFriends to be assigned. If @friends has the value

('Justin OMalley', 'Jeff Ellis', 'Brett Walters', 'Blake Escort')

$firstFriend will have the value ÕJustin OMalleyÕ, $secondFriend will have the value ÕJeff EllisÕ and @restFriends will have the value (ÕBrett WaltersÕ, ÕBlake EscortÕ). The value of @friends does not change.

If @friends was empty to begin with, the two scalar variables will have undef value and the array will be empty after the assignment. If @friends had only one element, only $firstFriend will be assigned. $secondFriend will have undef value and the array @restFriends will remain empty. An array used on the left hand side of the assignment is all-consuming in the sense that it will hog all remaining elements of the array given on the right hand side. So, although it is syntactically correct to write more than one array variable on the left hand side, anything following the first array variable will remain unassigned. For example, if we write

($firstFriend, $secondFriend, @someFriends, $middleFriend, @restFriends)= @friends;

the value of $middleFriend will always be undef. In addition, @restFriends will always be empty. This is because the array @someFriends will consume all elements that are left after @friends assigning values to the two scalars.

If we want to ignore the first element of the list when performing the assignment, we can write

(undef, $secondFriend, @someFriends, $middleFriend, @restFriends) = @friends;

The idea of using array literals can be used for swapping values of scalar variables. For example, if we write

($firstFriend, $secondFriend) = ($secondFriend, $firstFriend);

the values of the two variables are swapped.

The technique of extracting elements from an array is used quite frequently inside subroutines to extract specific arguments and give them specific names.