Variables help reserve memory to store values. The amount of memory space reserved depends on the data type of the variable declared. This means we can reserve different spaces for integers, decimals, strings, etc.
There are three basic data types in Perl:
$
. These store numbers, strings, or references.@
. These store-ordered lists of scalars.%
. These store sets of key-value pairs.Variables in Perl can be declared implicitly. The declaration of the variable occurs when we assign a value to it. The assignment is done by using a =
between the variable name on the left and the value on the right.
A scalar is a single unit of data which might be an integer, decimal, string, etc. This data may be of any type, but must consist of only one unit.
Arrays store ordered lists of scalars. A single element inside an array is referred to using the scalar indicator, $
.
Hashes store key-value pairs. To refer to a single element of a hash, the hash variable name is followed by the “key” associated with the value in curly brackets.
The following code shows how different variables are declared in Perl:
# Declaration of variables example# Scalar variablesprint "Scalar variables\n";$roll_num = 33333; # An integer assignment$name = "Lisa Sherbet"; # A string$score = 20.5; # A floating pointprint "Roll number = $roll_num\n";print "Name = $name\n";print "score = $score\n\n";# Array variablesprint "Array variables\n";@roll_nums = (23432, 32340, 42340);@names = ("John Paul", "Lisa", "Kumar");print "\$roll_nums[0] = $roll_nums[0]\n";print "\$roll_nums[1] = $roll_nums[1]\n";print "\$roll_nums[2] = $roll_nums[2]\n";print "\$names[0] = $names[0]\n";print "\$names[1] = $names[1]\n";print "\$names[2] = $names[2]\n\n";# Hash variablesprint "Hash variables\n";%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);print "\$data{'John Paul'} = $data{'John Paul'}\n";print "\$data{'Lisa'} = $data{'Lisa'}\n";print "\$data{'Kumar'} = $data{'Kumar'}\n";