Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to declare variables in Perl 5.34

Sheza Munir

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:

  • Scalars:
    Scalars are preceded by . These store numbers, strings, or references.
  • Arrays:
    Arrays are preceded by @. These store-ordered lists of scalars.
  • Hashes:
    Hashes are preceded by %. These store sets of key-value pairs.

Declaring variables

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.

Scalar variables

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.

Array variables

Arrays store ordered lists of scalars. A single element inside an array is referred to using the scalar indicator, .

Hash variables

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 variables
print "Scalar variables\n";
$roll_num = 33333;       # An integer assignment
$name = "Lisa Sherbet";   # A string 
$score = 20.5;     # A floating point

print "Roll number = $roll_num\n";
print "Name = $name\n";
print "score = $score\n\n";

# Array variables
print "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 variables
print "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";




Sheza Munir
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring