< Perl Tutorial

Perl scalars

← Previous Next →

Perl Scalars

A scalar can contain a single value such as a number or a string. It can also contain a reference to another data structure. The name of the scalar always starts with a $ (dollar sign) followed by letters, numbers and underscores. A variable name can be $name or $long_and_descriptive_name.
The following simple example demonstrates scalars:

$age = 25;             # An integer assignment
$name = "John Paul";   # A string 
$salary = 1445.50;     # A floating point

print "Age = $age\n";
print "Name = $name\n";
print "Salary = $salary\n";

In general we will be dealing with two different kinds of Scalar values. They are Numeric Scalars and String Scalars. Both of these are discussed below.

Numeric Scalars

The most common scalar values in Perl programs are integer scalar values, also known as integer constants or integer literals. An integer scalar value consists of one or more digits, optionally preceded by a plus or minus sign and optionally containing underscores.
Perl stores integers in the floating-point registers on our machine. In other words, integers are treated as if they are floating-point numbers (numbers containing decimal points). On most machines, floating-point registers can store approximately 16 digits before running out of space.
An example demonstrating numeric scalars in Perl:

$value = 1234567890;

print ("first value is ", $value, "\n");

$value = 1234567890123456;

print ("second value is ", $value, "\n");

The above program produces the following output:

first value is 1234567890

second value is 1234567890123456

String Scalars

A character string is a sequence of one or more letters, digits, spaces, or special characters. We can store string in a scalar variable in two ways. One is by using single quotes and the other by using doublw quotes. Perl renders the text inside single and double quotes differently. The text inside double quotes is interpolated to support Escape Sequences and other features whereas the text inside single quotes does not undergo interpolation and is displayed as is.
Following examples show how Perl renders the two types of qotes:

# Usage of Double Quoted Strings
$number = 11;

$text = "This text contains the number $number.";

$result = 14;

print("The value of \$result is $result.\n");

# Usage of Single Quoted Strings
$text = 'This is a string.\n';

$text = 'This string ends with a backslash \\';

The output of the above code is following:

This text contains the number 11.

The value of $result is 14.

This is a string.\n

This string ends with a backslash \


← Previous Next →