Perl Basics part 2: Scalars, Arrays, and Hashes

No Comments

In this part 2 section of perl basics, we will learn about perl scalars, arrays, and hashes which are heart of the perl language syntax.  In C, Java and C++ programming languages we call varibales which holds or stores data, here in perl we call it scalars.  Scalars are defined with prefixed ‘$’ symbols as shown below.

Scalars: also called variables

$i = 10;
$string = ‘Ramraj’;
$float = 1.005;
print “Int value is = $i n”;
print “String value is = $string n”;
print “Float value is = $float n”;

In above code snippet three variables or scalars are defined, and the first one $i  stores integer values, $string stores string value, and $float scalar is floating point value. Perl scalars can hold integers or numbers, string values, and decimal point values such as float, double etc. there is no need to define variable type unlike in java, C, and C++.  Perl is dynamic language and perl interpreter determines types automatically at runtime, this is one big benefit compare to those languages.

In the above code, three print statements prints the all three variables, and ‘n’ is new line character to print each line in a new line.

Arrays: List of scalars

Arrays are defined with prefixed ‘@’  symbol, which is called at symbol. Arrays store list of elements or scalars and provides mechanism to retrieve the values from the array. Arrays are very important and fundamental data structure for any programming languages.

array syntax:

@array = (1, 2, 3, 4, 5);  #list of integer values
@strarray = (‘ram’, ‘raj’, ‘jhon’, ‘mohan’);  #list of string values
print “List the integer array: @array n”
print “List the string array: @strarray n”
print “Print the first value: $array[0]“

Arrays are zero index based list means first values stores at zero index, and next value at 1st index and so on. Above you can see two arrays one with a list of integer values, and another array filled with string values. To print array values use index value with array scalar like $array[0] prints ’1′ , and $array[1] print ’2′.

Hashes: also called Dictionaries

Hashes are prefixed with ‘%’ symbol and defines name value pair mappings.

hashes syntax:

%ha = (“Ram” => 1, “Raj” => 2, “Bem” => 9, “hey” => 10);

print $ha{“Ram”} #prints value ’1′

We have now learned the basic data element structures and syntax in perl. Try yourself all above mentioned code samples and let me know if you have any problem in understanding.


Browse Realted Articles