Variables are used to store some value. Based on the data type of the variable, the interpreter allocates memory to the variable.
All variables in Perl must be in accordance with the following rules:
variable names must contain only letters (a-z, A-Z), underscores (_), and numeric digits (0-9).
The first character of a variable name must be a letter (a-z, A-Z) or underscore (_).
Variable names are case-sensitive, so thiscar is not the same as ThisCar.
The basic data types in Perl are:
In our examples, we will be creating variables of these three data types. A $
sign precedes a scalar variable, and it can store a number, string, or reference. An array variable is prefixed by @
, and it stores an ordered list of scalars. Finally, the hash variable is preceded by the &
and stores key-value pairs.
In Perl, we do not need to explicitly reserve space for the variable. Using the =
operator automatically creates space when we assign a value to the variable. The operand on the left of the =
operator is the variable name, and the operand on the right is the value stored in the variable.
We will create three scalar variables named name
, age
, and gender
in this example. A scalar is a single unit of data that can be of any data type, such as a character, a string, an integer, a floating point, a paragraph, or an entire web page.
$age = 15; # An integer assignment$name = "Usuf DePaul"; # A string$gender = "male"; # A stringprint "Age = $age\n";print "Name = $name\n";print "Gender = $gender\n";
An array stores a list of ordered scalar variables. This example shows how we can create arrays in Perl:
We use the
$
sign to access the elements of the array since the element is a scalar variable.
@order_nums = (1, 3, 55);@names = ("Jacob", "Kumar", "Dinesh");print "\$order_nums[0] = $order_nums[0]\n";print "\$order_nums[1] = $order_nums[1]\n";print "\$order_nums[2] = $order_nums[2]\n";print "\$names[0] = $names[0]\n";print "\$names[1] = $names[1]\n";print "\$names[2] = $names[2]\n";
A hash is a set of key-value pairs. To access the value associated with a key, we will use the hash variable name followed by the key in curly brackets:
%data = ("Jacob", 1, "Kumar", 3, "Dinesh", 55);print "\$data{'Jacob'} = $data{'Jacob'}\n";print "\$data{'Kumar'} = $data{'Kumar'}\n";print "\$data{'Dinesh'} = $data{'Dinesh'}\n";
Free Resources