3.1.2 Assigning Value to an Array
One can make an assignment to an array variable by specifying the values of the elements.
my @friends98 = ('John Hart', 'Jeff Ellis', 'Brett Walters', 'Blake Escort');
The values are given as a comma-separated list enclosed in parentheses. We can also assign an array to another array. When we write
@myFriends = @friends;
the value of @friends is assigned to @myFriends.
Elements of an array are scalars, but they need not be all strings or all numbers or all references. Mixing is allowed.
@numbers = (1, 2, "3", "four", 'five', 6);
When we write an array using parentheses and give all its values, we call it the literal representation of the array. In the assignment given above, (1, 2, "3", "four", ÕfiveÕ, 6) is the literal representation. When we assign value to an array using parentheses, we can have scalar variables inside the parentheses. Therefore, the following is correct assuming we have assigned values to $firstFriend, $secondFriend and $lastFriend already.
@friends = ($firstFriend, $secondFriend, 'Brett Walters',
'Justin OMalley', $lastFriend);
We can, in fact, intersperse scalar variables, literal scalars and array variables when we perform assignment. The following program fragment shows this.
my (@friends, $friend);
my @friends98 = ('John Hart', 'Jeff Ellis', 'Brett Walters', 'Blake Escort');
my $friend97 = "Tom Toybee";
my @oldFriends = ('Chad Blonding', "Jeff Perich");
my @friends = ("Hakan Kvarnstrom", @friends98, $friend97, @oldFriends);
Here the last assignment has a constant scalar string, a scalar variable, and two array variables in the literal array representation used on the right hand side of the assignment. The value of @friends at the end of the last assignment statement is given below.
("Hakan Kvarnstrom", 'John Hart', 'Jeff Ellis', 'Brett Walters', 'Blake Escort',
"Tom Toybee", 'Chad Blonding', "Jeff Perich");
An array variable such as @friends98, when used inside a list is opened up and its elements are placed where the variable name was. This is simply an example of variable flattening. In Perl, a list or an array is always only one level deep. That is, there are no embedded lists. In other words, an array is always one-dimensional. Also, it is not necessary to write the parentheses around a list unless needed. However, we need to know that the comma (,) is just a list element separator inside a list given inside parentheses. Outside a list in parentheses, it means something different. It then is the so-called comma operator that evaluates the left operand, ignores the result, evaluates the right operand, and returns its result.
