Scalar Variables
A variable is a name for a container that holds one or more values.[47] The name of the variable stays the same throughout the program, but the value or values contained in that variable typically change repeatedly throughout the execution of the program.
A scalar variable holds a single scalar value as you’d expect. Scalar variable names begin with a dollar sign followed by what we’ll call a Perl identifier
: a letter or underscore, and then possibly more letters, or digits, or underscores. Another way to think of it is that it’s made up of alphanumerics and underscores but can’t start with a digit. Uppercase and lowercase letters are distinct: the variable $Fred is a different variable from $fred. And all of the letters, digits, and underscores are significant:
$a_very_long_variable_that_ends_in_1
The preceding line is different from the following line:
$a_very_long_variable_that_ends_in_2
Scalar variables in Perl are always referenced with the leading $.[48] In the shell, you use $ to get the value, but leave the $ off to assign a new value. In awk or C, you leave the $ off entirely. If you bounce back and forth a lot, you’ll find yourself typing the wrong things occasionally. This is expected. (Most Perl programmers would recommend that you stop writing shell, awk, and C programs, but that may not work for you.)
Choosing Good Variable Names
You should generally select variable names that mean something regarding the purpose of the variable. For example, $r is probably ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access