O'Reilly logo

Learning Perl, Fourth Edition by brian d foy, Tom Phoenix, Randal L. Schwartz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required