- An array variable can appear in the list to the left of the equal
operator, but it must be the last in the list, as it will be
greedy and take the remainder of the values.
- Example:
@First = (1, 2, 3, 4, 5);
($One, $Two, $Three, @Rest) = @First;
print "One=$One, Two=$Two, Three=$Three\n";
==> One=1, Two=2, Three=3
print "@Rest\n";
==> 4 5
- If a scalar variable is assigned equal to an array, then the
scalar gets the current length of the specified array.
- Example:
@First = (1, 2, 3, 4, 5);
$FirstLength = @First;
print "FirstLength = $FirstLength\n";
==> FirstLength = 5
- Remember that in Perl, it is the operator being used that
determines the variable type, not a variable declaration. Therefore,
if you use an operator that requires a scalar context (as opposed to
an array context), then you get the length of the array instead of the
contents of the array.
- Example:
@First = (1, 2, 3, 4, 5);
$theFirst = @First; # Scalar context so get length
print "theFirst = $theFirst\n";
==> theFirst = 5
($theFirst) = @First; # Array context, so get first value, ditch rest
print "theFirst = $theFirst\n";
==> theFirst = 1
- Just like with scalars, the assignment operator for arrays returns
the array being assigned. This allows chaining of assigments.
- Example:
@First = (@second = (@Third = (1, 2, 3, 4, 5)));