Scalar Values and Scalar Variables

A scalar value is a single item of data, like a string or a number.

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 to represent a newline (see Table B-3):

$aside = '(or so they say)';
$declaration = "Misery
 $aside 
loves company.";
print $declaration;

This snippet prints out:

Misery 
 (or so they say) 
loves company.

Numbers

Numbers are scalar values that can be:

  • Integers:

    3
    -4
    0
  • F loating-point (decimal):

    4.5326
  • Scientific (exponential) notation (3.13 x 1023 or 313000000000000000000000):

    3.13E23
  • Hexadecimal (base 16) :

    Ox12bc3
  • Octal (base 8):

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

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset