B.3
Scalar Values and Scalar Variables
A
scalar value is a single item of data,
like a string or a number.
B.3.1
Strings
Strings are scalar values
and are
written as text enclosed within single quotes, like so:
'This is a string in single quotes.'
or double quotes, such as:
"This is a string in double quotes."
A single-quoted
string prints out exactly as written. With double quotes, you can
include a variable in the string, and its value will be inserted or
"interpolated." You can also include commands such as
\n to represent a newline (see Table B-3):
$aside = '(or so they say)';
$declaration = "Misery\n $aside \nloves company.";
print $declaration;
This snippet prints out:
Misery
(or so they say)
loves company.
B.3.2
Numbers
Numbers are
scalar values that
can be:
-
Hexadecimal (base 16) :
Ox12bc3
-
Binary (base 2):
0b10101011
Complex (or imaginary) numbers, such as
3 + i,
and
fractions
(or ratios, or rational numbers), such as 1/3, can
be a little tricky. Perl can handle fractions but converts them
internally to floating-point numbers, which can make certain
operations go wrong (Perl is not alone among computer languages in
this regard.):
if ( 10/3 == ( (1/3) * 10 ) {
print "Success!";
}else {
print "Failure!";
}
This prints:
Failure!
To properly handle rational arithmetic with fractions, complex
numbers, or many other mathematical constructs, there are mathematics
modules available, which aren't covered here.
B.3.3
Scalar Variables
Scalar values can be stored in
scalar
variables. A scalar
variable
is indicated with a $ before the variable's
name. The name begins with a letter or underscore and can have any
number of letters, underscores, or digits. A digit, however,
can't be the first character in a variable name. Here are some
examples of legal names of scalar variables:
$Var
$var_1
Here are some improper names for scalar variables:
$1var
$var!iable
Names are case sensitive: $dna is different from
$DNA.
These rules for making proper variable names (apart from the
beginning $) also hold for the names of array and
hash variables and for subroutine names.
A scalar variable may hold any type of scalar value mentioned
previously, such as strings or the different types of numbers.