Variable Syntax
A variable is just a handy place to keep something, a place with a name,
so you know where to find your special something when you come back
looking for it later. As in real life, there are various kinds of places
to store things, some of them rather private, and some of them out in
public. Some places are temporary, and other places are more permanent.
Computer scientists love to talk about the “scope” of variables, but
that’s all they mean by it. Perl has various handy ways of dealing with
scoping issues, which you’ll be happy to learn later when the time is
right. Which is not yet. (Look up the adjectives local, my,
our, and state in Chapter 27, when you
get curious, or see Scoped Declarations in Chapter 4.)
But a more immediately useful way of classifying variables is by what sort of data they can hold. As in English, Perl’s primary type distinction is between singular and plural data. Strings and numbers are singular pieces of data, while lists of strings or numbers are plural. (And when we get to object-oriented programming, you’ll find that the typical object looks singular from the outside but plural from the inside, like a class of students.) We call a singular variable a scalar, and a plural variable an array. Since a string can be stored in a scalar variable, we might write a slightly longer (and commented) version of our first example like this:
my $phrase = "Howdy, world!\n"; # Create a variable. print $phrase; # Print the variable.
The my tells Perl that ...
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