How to use variables and array in perl

What is Perl?

The full form of PERL is “Practical Extraction and Reporting Language“. PERL is invented by Larry Wall in 1987. It is a high-level, interpreted, powerful dynamic programming language. It is a portable and cross-platform language and free to use. It is used for doing various types of tasks like network programming, automation, system administration, database management, implementing GUI, web programming etc. It is developed based on other languages such as BASIC, awk, sed, C etc.

Features of PERL:

Some important features PERL are mentioned below.

  • It is an open-source software
  • It is easy to learn.
  • It can be used with other scripting languages like HTML, XML etc.
  • It supports Unicode.
  • It is extensible.
  • It supports third party databases, such as Oracle, MySQL, PostgreSQL etc.

Install PERL on Ubuntu:

You don’t need to install PERL on Ubuntu because it is installed by default on Ubuntu operating system. Run the following command to check the installed version of PERL.


$ perl --version

Run Your First PERL script:

Create a file with the extension ‘.pl’ and add the following script to print a simple text. Using ‘;’ at the end of each statement is necessary in PERL.

first.pl


#!/local/bin/perl

print "Welcome to PERL Programming";

Run the script.

$ perl first.pl

PERL Variables:

Three types of variables are supported by PERL. These are,

Scalar
It is declared by $ symbol. It can be any number or string or reference variable.

Arrays
It is used to declare ordered list of scalar data. @ symbol is used to declare this type of array.

Hashes
It is used to declare unordered list of scalar data with key/value pairs. % symbol is used to declare this type of variable.

Example:

Three types of variable declarations are shown in the following example. Create a PERL script file with the following script.
var.pl

#!/local/bin/perl

#Scalar variables
$int_var = 7;
$str_var = "PERL Scripting Language";
$float_var = 89.56;
print $int_var,"\n",$str_var,"\n",$float_var;

# Array variables
@score = (75, 78, 97, 55, 34);
@country = ("Afghanistan ", "France ", "Bangladesh ");
print "$score[1]\n";
$len = @score;
print "$len\n";
print @country;

# Hash variables
%marks = ('Afia' => 85, 'Hossain' => 60, 'Robin' => 74);
print "$marks{'Hossain'}\n";
%population = ('Dhaka', 7466669, 'Comilla', 8966634, 'Bogra', 76366445);
print "$population{'Comilla'}\n";

Run the script.

$ perl var.pl

PERL Reference variable:

Reference variable share the same memory space of the main variable. This example shows the use of reference variable for three types of PERL variables. Create a PERL file with the following script.

Example:

ref.pl

#!/local/bin/perl

#Referencing scalar variable
$website = "fahmidasclassroom.com";
# $url references to $website
$url = \$website;
# Print the value of reference variable.
print "The website address is : ", $$url, "\n";

#Referencing array variable
@myarr = ("Good ", "Bad ", "Ugly ");
# $refarr references to @myarr array.
$refarr = \@myarr;
# Print the value of $refarr.
print "The values of reference array are: ", @$refarr, "\n";

#Referencing hash variable
%students = ('1001:' => 'Abir ', '1002:' => 'Kabir ', '1003:'=>'Nibir ' );
# $refstd references to @students hash
$refstd = \%students;
$students{'1003:'} = "Alamgir ";
# Print the value of $refstd
print "The values of reference array are: ", %$refstd, "\n";

Run the script.

$ perl ref.pl

Exercise:

Create an associative array of five persons that contains name as key and favorite food as value. Change the favorite food of the third person by using reference and print the main array.

Insert and remove array data

Two built-in function can be used in PERL to insert data into an array. These are push() and unshift(). push() function is used to insert data at the end of the array and unshift() function is used to insert data at the beginning of the array. There are two other functions in PERL to remove data from the array. pop() function is used to remove data from the ending and shift() function is used to remove data from the beginning. So, push() and pop() work on LIFO based and shift() and unshift() work on FIFO based. The following example shows the uses of these functions.

Example:

insdel.pl

#!/local/bin/perl

@months = ("January ","February ","March ","April ");
#Insert data at the end
push(@months,"May ");
#Print the array
print @months,"\n";

#Remove data from the end
pop(@months);
#Print the array
print @months,"\n";

@weekday = ("Monday ","Tuesday ","Wednesday ","Thursday ","Friday ","Saturday ");
#Insert data at the beginning
unshift(@weekday,"Sunday ");
#Print the array
print @weekday,"\n";

#Remove data from the beginning
shift(@weekday);
#Print the array
print @weekday;

Run the script.

$ perl insdel.pl

Exercise:
Create an array of 10 course names, insert two new courses at the end of the array and delete the first course from the array and print the array.

Sorting Array

PERL contains a built-in function, sort() to sort the array elements in ascending order. The following example shows the use of the sort function.

Example:
srt.pl

#Declare Array of numbers
@a = (30, 21, 51, 49, 37, 16); 
print "Before sort: ", "@a","\n"; 
#Sorting numeric data
@a = sort {$a <=> $b} @a; 
print "After sort: ","@a","\n"; 

#Declare array of strings
@flowers = ("Rose", "Lily", "Tulip", "Water Lily");
print "Before sort: ", "@flowers","\n"; 
@sortarr = sort @flowers;
print "After sort: ", "@sortarr","\n";  

Run the script.

$ perl srt.pl

Traverse array using loop

All array elements are printed in a single line in the previous all examples used in this tutorial. You have to use loop to print each array element in seperate line. For loop is used in the following example to print array elements in separate lines. Here, split() function is used to create array from a string data.

Example:
arrloop.pl

print "Enter a text"
#Take input 
$text = <>;
#create the array
@myarr=split(' ',$text);
#Print each element separately using loop
foreach(@myarr)
{
    print "$_ \n";
}

Run the script.

$ perl arrloop.pl

Exercise:
Write a PERL script to take a text of comma(,) separated data that contains student name, department, batch and semester from the user, seperate each data from the text and print each data in separate lines.

For Example:
Input: Abir Hossain,CSE,43,10
Output: Student Name: Abir Hosssain
Department: CSE
Batch: 43
Semester: 10

Conclusion:

Hope, this tutorial will help you to get basic knowledge of PERL and start PERL programming.