Perl Scalars
What is a scalar variable?
-
You can think of a variable as a "place holder", or a "name" that represents
one or more values. The generic syntax for defining scalar variables (also
known as variables for short) is as follows:
$variable_name = value;
Thus, for example, we might assign the value of twenty-seven to the scalar
variable named "age" with the syntax:
$age = 27;
The dollar sign ($) is used to let Perl
know that we are talking about a scalar variable. From then on, unless
we change the value of $age, the script will translate it to twenty-seven.
So if we then say:
print "$age\n";
Perl will send the value "27" to standard output, which in our case, will
be the Web browser.
If we are assigning a word or a series of words to a scalar variable rather
than just a number, we must mark the boundary of the value with single
or double quotes so that Perl will know "exactly" what should be assigned
to the scalar variable.
We use single quotes to mark the boundary of a plain text string and we
use double quotes to mark the boundary of a text string that can include
scalar variables to be "interpolated". For example, we might have the following
lines:
$age = 27;
$first_name = 'Selena';
$last_name = 'Sol';
$sentence = "$first_name $last_name is $age";
print "$sentence\n";
The routine would print the following line to standard output:
Selena Sol is 27
Notice that the scalar variable $sentence is assigned the actual values
of $first_name and $last_name. This is because they were "interpolated"
since we included them within double-quotes in the definition of $sentence.
There is no interpolation inside single quotes. Thus, if we had defined
$sentence using single quotes as follows:
$sentence = '$first_name $last_name is $age';
Perl would print the following to standard output:
$first_name $last_name is $age
Exercise
Three
Table of Contents
Using Scalars
|