Understanding Variables in Perl with example

After looking at simple program to print Hello World in Perl and understanding syntax used in Perl language, we will see one of the important part of the Perl programming which is Understanding variables in Perl language.

Variables in Perl

Perl has three types of variables: scalars, arrays and hashes. You can think them as for scalars as things, arrays as lists and hashes as dictionaries.

Lets see these variables in brief we will be discussing those in detail in upcoming articles about these variables.


First variable is scalar : A scalar represents a single value which can be String, Integer type or float number. In Perl we do not need to require to pre declare variable types.

Scalars example in Perl

# Perl program to print scalars
$word = "word";
$number = 777;
$floatnumber = 1.23;

print "$word\n";
print "$number\n";
print "$floatnumber\n";


Next variable type is Array which represents list of values. Arrays are zero indexed and $#array denotes the index of the last element of an array. Lets see example below to know more of this Array variable type :

Array example in Perl

# Perl program to print array
my @word = ("firstword","secondword","thirdword","fourthword");
my @number = (111,222,333,444,555);
my @gangajamuna = ("firstword",111, 6.66);

#Printing individual value in array
print "$word[0]\n";
print "$number[1]\n";
print "$gangajamuna[2]\n";

#Printing multiple values of array
print "@number[1..3]\n";

#Printing element at last index

print "@gangajamuna[$#gangajamuna]\n";

#Sorting array

@sortedArray = sort @word;
@reverseArray = reverse @word;

print "Original array\n";
print "@word[0..$#word]\n";print "After sorting\n";
print "@sortedArray[0..$#sortedArray]\n";
print "After reversing\n";
print "@reverseArray[0..$#reverseArray]\n";

As we can see in above example sort and reverse are the built in functions of Perl which are used for sort and reverse respectively.


Next important variable type is Hash.
Hash represent key-value pairs where hash index can be number or String.

Hash example in Perl

# Perl program to print hash variable
my %monthHash = ("1","January","2","February");
my %monthHash1 = (
"1" => "January",
"2" => "February"
while (($key, $value) = each(%monthHash)){
print $key.", ".$value."\n";

Here in above example we can see that for defining the hash we need prefix as %.

Note : .Variable names are case sensitive $abc, $Abc, $ABC are all different variables.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment