Variables

A variable always begins with the character that identifies its type: $, @, or %. Most of the variable names you create can begin with a letter or underscore, followed by any combination of letters, digits, or underscores, up to 255 characters in length. Upper- and lowercase letters are distinct. Variable names that begin with a digit can contain only digits, and variable names that begin with a character other than an alphanumeric or underscore can contain only that character. The latter forms are usually predefined variables in Perl, so it is best to name your variables beginning with a letter or underscore.

Variables have the undef value before they are first assigned or when they become “empty.” For scalar variables, undef evaluates to 0 when used as a number, and a zero-length, empty string (“”) when used as a string.

Simple variable assignment uses the assignment operator (=) with the appropriate data. For example:

$age = 26;                # Assigns 26 to $age
@date = (8, 24, 70);      # Assigns the three-element list to @date
%fruit = ('apples', 3, 'oranges', 6); 
 # Assigns the list elements to %fruit in key/value pairs

Scalar variables are always named with an initial $, even when referring to a scalar value that is part of an array or hash.

Every variable type has its own namespace. You can, without fear of conflict, use the same name for a scalar variable, an array, or a hash (or, for that matter, a filehandle, a subroutine name, or a label). This means that $foo and @foo are two ...

Get Perl in a Nutshell, 2nd 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.