To store scalar data in Perl, you must use a scalar variable. In Perl, you indicate a scalar variable with a dollar sign followed by the name of the variable. The following are some examples:
$a $total $Date $serial_number $cat450
The dollar signcalled a type identifierindicates to Perl that the variable contains scalar data. Other variable types (hashes and arrays) use a different identifier or no identifier at all (filehandles). Variable names in Perlwhether for hashes, arrays, filehandles, or scalarsmust conform to the following rules:
Variable names can contain alphabetic (a to z, A to Z) characters, numbers, or an underscore character (_) after the type identifier. The first character of a variable name can't be a number, though.
Variable names are case sensitive. This means that upper- and lowercase are significant in variable names. Thus, each of the following represents a different scalar variable:
$value $VALUE $Value $valuE
Perl reserves to itself single-character variable names that do not start with an alphabetic character or underscore. Variables such as $_, $", $/, $2, and $$ are special variables and should not be used as normal variables in your Perl programs. The purpose of these special variables will be covered later.
Scalar variables in Perlin contrast to some other languagesdo not have to be declared or initialized in any way before you can use them. To create a scalar variable, just use it. Perl uses a default value when an uninitialized variable is used. If it's used as a number (such as in a math operation), Perl will use the value 0 (zero); if it's used like a string (almost everywhere else), Perl will use the value "", the empty string.
Using a variable before it has been initialized with a value is considered a bad programming practice. Perl can be made to warn you when this situation happens. If your program has -w on the #! line at the beginning, or if you invoke Perl with the -w switch on the command line, then if you try to use the value of a variable that you haven't previously set, Perl responds with this error message when your program runs and you try to use the value: Use of uninitialized value.
The Special Variable $_
Perl has a special variable, $_, whose value is used as a "default" by many operators and functions. For example, if you simply state print by itselfwithout specifying a scalar variable or string literal to printPerl will print the current value of $_:
$_="Dark Side of the Moon"; print; # Prints the value of $_, "Dark Side..."
Using $_ like this can understandably cause some confusion. It's not really apparent what print is actually printing, especially if the assignment to $_ occurs higher up in the program.
Some operators and functions are actually easier to use with the $_variable, notably the pattern-matching operators discussed in Hour 6, "Pattern Matching." In this book, however, I'll keep the use of $_to a minimum so that the lessons are easier to follow.