Learn Perl in 2 hours: hour-1

Introduction:
Perl was originally developed for string manipulation and unix scripting in 1987, since then it has evolved and now its mainstream programming language which is used for a wide range of tasks including system administration, web development, network programming and GUI development. The best thing about Perl is that it's easy to use, efficient and complete. It supports both procedural and object-oriented programming (OOP), it has powerful built-in support for text processing as well and it also has impressive collections of third-party modules. Perl comes per-installed on unix systems, if its not or you are using windows system then download its installer and make sure that perl can be found in your system classpath. In this tutorial I have provided enough example code with explanation directly written above the code as a comment. Please copy this code, run it and play with it while learning.

Hello World:
Perl code can be written in simple text editor, I am using vim on unix. Create hello.pl file and put following code into this file. To run this program just type on command line: hello.pl
#!/usr/bin/env perl

# Its a good practice to start perl file with below two lines.
# It will stop execution of program if a potential problem occurs.
use strict;

# Only generates warning but let program continue when a potential problem occurs.
use warnings;

print "Hello World \n";
Variables:
Variables in perl can be defined in two ways one starting with 'my' keyword and other without it. Defining a variable with keyword 'my' is recommended as it stricts the scope of variable within the intended context when program executes.
# Scalar holds single value, starts with $
my $scalar_var = "I am scalar";

# Array holds multiple value, starts with @
my @array_var = (1,2,3,4,5);

# Hash holds multiple value, starts with %
my %hash_var = (1,'red',2,'green',3,'blue');
my @keys = keys %hash_var;
my @values = values %hash_var;

# To print a value stored in a variable, just put it with $/@ sign in double quote after print
# keyword, To print only integer there is no need to put it in double quote.
print "scalar_var = $scalar_var \n";
print "array_var = @array_var \n";
print "hash_keys = @keys, hash_values = @values \n";

# Multi-line print without \n
print <<ANYMARKER; 
To write multiple lines without using new line character in perl you have to 
follow a syntax starting with << and then  a string then and then actual string 
content. And then in a new line you have to close that delimeter string.
ANYMARKER

Output:
scalar_var = I am scalar
array_var = 1 2 3 4 5
hash_keys = 1 3 2, hash_values = red blue green
To write multiple lines without using new line character ...

Conditions:
print "Enter a number \n";
my $num = readline STDIN;
chomp $num;

# Simple if
if($num > 10) {
 print "From if: > 10, val: $num \n";
}

# if-else
if($num > 10) {
 print "From if-else: > 10, val: $num \n";
}
else {
 print "From if-else: < 10, val: $num \n";
}

# if-elseif
if($num > 10) {
 print "From if-elseif: > 10, val: $num \n";
}
elsif($num < 10) {
 print "From if-elseif: < 10, val: $num \n";
}

# if-elseif-else
if($num > 10) {
 print "From if-elseif-else: > 10, val: $num \n";
}
elsif($num < 10) {
 print "From if-elseif-else: < 10, val: $num \n";
}
else {
 print "From if-elseif-else: = 10, val: $num \n";
}

# Opposite of if, elseif and else can also be written with unless but it will become confusing
unless($num == 10) {
 print "!= 10\n";
}

# While loop, runs as long as condition is true
my $count = 1;
while ($count <= 5) {
 print "From while -> $count \n";
 $count++;
}

# Until loop, runs as long as condition is false
until ($count == 1) {
 print "From until -> $count \n";
 $count--;
}

# For loop, useful for iterating a list
my @days = qw(mon tue wed thu fri sat sun);
for my $i (1..5) {
 print "From for -> $i \n";
}
for (my $i = 1; $i <= 5; $i++) {
    print "From C style for -> $i \n";
}
for (@days) {
 print "From for, value in \$_ = $_ \n";
}
foreach my $day (@days) {
 print "From foreach = $day \n";
}

# do-while
do {
 print "From do-while $count \n";
 $count++;
} while($count <= 3);

# do-until
do {
 print "From do-until $count \n";
 $count--;
} until($count == 1);
Arrays:
my @months = ('jan', 'feb', 'mar');
print "Array printing = @months\n";

# Same Array can contain multiple types
my @array = (1, 2,'3',"4");
print "Printing 1st element of an array = $array[0] \n";

# qw is short of Quoted word which is used to declare string array
my @myArray = qw(My Name is Mukesh);

# One array variable can be assigned to another one
@myArray = @array;

# You can also put an array inside an array declaration, new array will be union of all elements
my @array2 = (@array, @myArray);

# Array of ints can be defined using ..
my @array3 = (1..20);

# Multiple assignment
(my $x1, my $x2, my $x3) = (1, 2, 3);
print "Multiple assignement x=$x1, y=$x2, z=$x3 \n";

# Swap
($x1, $x2) = ($x2, $x1);
print "Swapping values x=$x1, y=$x2 \n";

# Variable and list declaration in a single line
(my $y1, my @y2) = (1, 2, 3, 4);
print "Printing variable a=$y1, list b[0]=$y2[0]) \n";

($y1, @y2, my $y3) = (1, 2, 3, 4, 5, 6);
print "Printing variable a=$y1, list b[0]=$y2[0]), c=$y3 \n";

# Two ways to get size of an array
my $size1 = scalar @y2;
my $size2 = @y2;
print "scalar \@b = $size1, assignment of an array to a scalar = $size2 \n";

# $#varname is used to get index of last element of an array
my @z1 = (1..100);
print "Last index of an array of 100 elements = $#z1 \n";

my @z2 = ();
print "Last index of an empty array = $#z2 \n";

my $z3 = shift @z2;
print "shift removes first element of an array and assigns it to the variable s=$z3, $z2[0] \n";

unshift(@z1, "first");
print "unshift replaces first element of an array, now d[0] = $z1[0] \n";

# Similar to shift and unshift there is pop and push function which operates on last element
# Reverse is a function to reverse an array
@z1 = reverse(@z1);
print "Reversed array d[0] = $z1[0] \n";

my @testarray = qw(e T c d);
print "Printing an array @testarray, size $#testarray \n";

my @sorted = sort (@testarray);
print "Sorted array @sorted \n";

my @num = qw(1 2 3 22 11 0 23 5);
my @num = sort {$a <=> $b} @num;
print "To sort numerically you have to use {\$a <=> \$b}  @num \n";

# splice function is used to remove n number of elements from an array.
# It returns removed elements
splice (@num, 1, 3);
print "Applying splice which will remove 1st, 2nd and 3rd element from num array @num \n";
Hash:
# hash can be defined just like array, but interpertation becomes different
# in case of has each pair becomes key-value.
my %hash = qw(1 2 3 22 11 0 23 5);
my @values = values %hash;
print "@values \n";

my %country_map = ("India", "Delhi", "USA", "New York", "Japan", "Tokyo");

# Another way to define hash
%country_map = (
    India => "Delhi",
    USA => "New York",
 Japan => "Tokyo"
);
my $indiaCapital = $country_map{"India"};
print "$indiaCapital \n";

my @countries = keys %country_map;
my @capitals = values %country_map;
File Handling:
Save below content in a file 'file.pl', modify the code accordingly like change filename etc.. Run with command file.pl arg1 arg2 ... where arg1, arg2 are filenames.
#!/usr/bin/perl

use strict;
use warnings;

# STDIN is the standard input handle while <STDIN> is the content of the handle
# chop removes last character 
# chomp removes last character only if it is new line, this is special version of chop
print "Enter your name \n";
my $name = <STDIN>;
chomp $name;
chop($name);
print "Your name = $name \n";

# Opening a file, Open with any marker here 'IN' then $. and $_ contains line number and line
# content, $! returns error. It reads one line at a time in $_ variable
open IN,"temp.txt" or die "Error in opening $!";
while (<IN>) {
 print "$.| $_";
}
close IN;

# Writting in a file, > sign means you are opening this file for output
open OUT, ">out.txt" or die "Error in opening $!";
for my $i (1..20) {
 print OUT "$i :: Hello, The time is", scalar(localtime) ," \n";
}
close OUT;

# Appending to a file, use >> instead of > and do what you did in case of writting
open OUT, ">>out.txt" or die "Error in opening $!";
for my $i (1..20) {
 print OUT "$i :: Hello, The time is", scalar(localtime) ," \n";
}
close OUT;

# Printing a file, $_ is the default variable so if we don't give anything to print then $_
# value will be printed.
open AP, "out.txt" or die "Error in opening $!";
while (<AP>) {
 print;
}
close AP;

# @ARGV is a special array which will hold parameters passed with perl command
foreach (@ARGV) {
 print;
 print "$_ \n";
}

# STDIN, STDOUT, STDERR, ARGV these 4 are important constructs in perl
# @ARGV is used to store commandline arguments whereas <argv> will each file in turn which is
# again specified in commandline, if no file is specified then it starts reading from standard 
# input, shortcut for <argv> is <>
foreach(<>) {
 print "$. : $_";
}
In the next part I'll talk about subroutines and Object Oriented Programming in Perl.

8 comments: