Learn Perl programming in two days – Day one

Satya Perl Tutorial , , , ,

  Next  (go to Day two tutorial)

Day one – Learn Perl programming in two days

Learn perl programming in two days
                                                                               Image: Learn Perl programming in two days

Perl is Practical extraction reporting language written by Larry Wall in 1987. Initially, designed for text processing, but later on it evolved so much so that now a days it is being used for almost every thing, these are like Web applications, Database programming, Biotechnology, and in many scientific research.

It is also known as Swiss  army knife, as it does lot of things and very versatile. Perl Philosophy is to do one task in many possible ways.It is a interpreter language. So, one has to just write code and run. There is no need to compile the program.

 

 

Perl installation

In Ubuntu, or any Unix machine Perl is already installed, but if required we can install any other Perl version. In Ubuntu, run below command to install Perl.

   >sudo apt-get install Perl

Check the version of Perl.

   >perl -v 

Run yum command to install in Red Hat Linux

   >yum install perl

In window, download Active Perl and then install.

Run Perl program: Write Perl script by using any of your favorite editor.

In UNIX system, you can use vi or vim. Below code snippet shows hello world program. Here, you have to use shebang at first line, it call the Perl binary file. Remaining lines uses print function to display “Hello world” on console. Write these lines in a file then save it. You can give extension as .pl to the file. In UNIX it is not necessary give extension.

 

Write below code and save it in a file first_program.pl.

    #!/usr/bin/perl
    print (“Hello world\n”);
    print “hello world\n”;

In order to run this code in Unix machine you have to change the permission of the script to make it executable. Use Unix command “chmod” to change the permission.

    >chmod 755 first_program.pl

You can run this program in two ways on UNIX prompt. Note: Comment start with ‘#’  except in shebang.

    >./first_program.pl     # First way, In this case make sure shebang line is defined
    > perl first_program.pl # second way
    > Hello world           # Output

As a result, both way will print hello world.

 

In window, open cmd and go to the location where you have save the Perl program, and then run below command.

     perl first_program.pl

Perl Numeric and String

Numeric

There are different forms of numeric data in Perl. Following are the types:

   Numeric Type               Value
   Integer                    123
   Negative Integer           -1100
   Floating point             7.10
   Octal                      0277
   Scientific notation        145.11E17
   Hexadecimal                #3FA7

String

String can be placed in single or double quote.

e.g of Single-Quoted Strings

  'world’
  ‘don\’t’             # five characters: d, o, n, single-quote  and t
  'hello\n‘            # Here \n will be considered as characters rather than new line
  ‘hello
   john'

e.g. of Double-Quoted Strings

  "hello how are you\n“    # here \n will considered as new line
  "coke \t  sprite”        # Here \t is tab

 

Escape sequences, which can be used in double quote

  Escape   sequence:- 
  \n       Newline
  \r       Carriage return
  \t       Horizontal tab
  \\       Backslash
  \'       Single quote
  \"       Double quote
  \a       Alert or bell
  \b       Backspace
  \f       Form feed
  \u       Forces next character to uppercase
  \l       Forces next character to lowercase
  \U       Forces all following characters to uppercase
  \L       Forces all following characters to lowercase
  \Q       Backslash all following non-alphanumeric characters
  \E       End \U, \L, or \Q
  \0nn     Creates Octal formatted numbers
  \xnn     Creates Hexadecimal formatted numbers


Comment in Perl

Comment in Perl begin with ‘#’

   # this is comment
   # more comment

Multi line comments, it is written in below way, where it begins with ‘=comment’. You can name any thing but it should being with ‘=’, and the comment must end with =cut.

   = comment
   Every thing written here will not
   be considered as code
   This is the way multi-line comment is written
   =cut
   print "hello world\n";
   
Here, execution of only print statement(last line) will take place. Rest all other
lines are comments.

 

Scalar Variables

A scalar variable is a name for a container that holds one or more values. It is a simple variable which store character, string or number. Scalar variable is prefixed by ‘$’ sign. There are  255 characters, which can be used for variable name. Following are valid variable names:

  • $a_very_long_variable_that_ends_in_8  #is valid variable name.
  • $var is different than $VAR, so it is case sensitive.
  • $xyz123 is   probably not very descriptive but $line_width is.

 

 Scalar Operators

Assignment operator:  The most common operation on a scalar variable is assignment  ( = ), which is the way to assign value to a variable.

   $a = 17;                       # Assigned value 17 to Variable $a
   $string_var = ‘Hello world’;   # String Hello world assigned to $string_var
   $string_var2 = “Hello world”;  # Hello world string assigned to inside double quote

  
Interpolation of Scalars into Strings
   $a = "shown";
   $b = "some text $a";            # $b is now "some text shown
   $c = "no such variable $what";  # $c is "no such variable“ as $what is not
                                   # defined

   print "$a\n";
   print "$b\n";
   print "$c\n";

You can’t do double substitution.

   $bar='John'
   $x = '$bar';          # literally a dollar sign followed by "bar“
   $y = "hey $x";        # value is 'hey $bar': no double substitution, 
                         # Value of $bar, which is John, will not be evaluated


When variable used in interpolation make sure there should be space after it or else it will be considered as different variable.

   $foo = "Every";
   $barney = "It's $foothing";       # this will not be ‘Everything’

We can use curly braces for this.

   $barney = "It's ${foo}thing";     # this will be Everything

 

Addition

Addition of two numbers, 10 and 55.

   $a=10
   $b = 55
   $result = $a + $b   
   print “$result”;    # result will be 65
   print 55 + 10 ;     # same thing we can do in one line

 

Subtraction

Subtraction of two numbers, 24 and 7.

   $a=24;
   $b = 7;
   $result = $a - $b; # result will be 17
   print "$result\n";

 

Multiplication

Multiplication of two numbers, 3 and 5.

   $mul = 3 * 5;     # result will be 15
   print "$mul\n";

 

Division

Division of two numbers, 4 and 2.

   $result = 4 / 2 ;  # result will be 2
   print "$result\n";

 

Modulus

   $result = 14 % 7   # result will be 0 (remainder)
   $result = 14 % 3   # result will be 2 (remainder)

 

Exponent

   $result = 10 ** 2  # result will be 100

 

Binary Assignment

Binary operation can be Performed by following ways.

   $a = $a + 5;
   $a += 5;       # same as $a = $a + 5;

   $b = $b * 3;
   $b *= 3;       # same as $b = $b * 3;

 

Auto increment and Auto decrement

Increment and decrement is useful in loops.


   ++$a     
   $a++;   # Same as $a=$a+1;
 
 
   --$a 
   $a--    # Same as $a = $a -1 ;

 

Concatenation

We can join two strings or characters by using concatenate operator ( .), and similarly we can join number and string as well.

   $str = "hello" . "John";         # Joining two worlds
   $mix = $str . 15;                # Combining ’15’ and ‘Hello John’ to 
                                    # make it ‘hello John15’
   print “found” . 4+3 . “items\n”; # Here ouput will be "found 7 items"

We can Join several words and assign it to variable in order to form a big sentence by using concatenate operator with assignment operator (.=).

   $var  = "hello";
   $var .= " how";                   # Same as $var = $var . “ How”
   $var .= " are";
   $var .= " you?";
   print "$var\n";                   # Output will be "Hello How are you?"

 

Repetition(x)

Some time we have to write particular character several times. This is useful for reporting purpose, so instead of keep typing that character, we can  use ‘repetition operator ‘x‘(small letter).

   print “_” x 7 . “\n”;    ## 7 times underscore
   print 8 x 9 . “\n”;      ## 888888888

  Note: Printing character/number should always be at left side of ‘x’.

 

 

Converting string into upper case or lower case

Convert all the characters in a string to upper case by using “uc” function. Function “lc” is to convert every thing in lower case and “ucfirst” is to convert first letter of a string in upper case.

   $upper_case = uc ($string);  
   $lower_case = lc ($string);
   $first_u = ucfirst ($string);

 

The chop and chomp Functions

Chop remove last character in a string and chomp remove record separator ($/) from string, $/ is mostly set as newline.


   $x = "hello world";
   chop($x);               # $x is now "hello worl", letter 'd' is removed


   $a = "hello world\n";
   chomp ($a);            # $a is now "hello world", \n newline is removed  

 

Getting the value from standard input

User can pass value to a program through standard input code.

   $a = <STDIN>;        # program wait until user provide value, this get assigned to $a 
   chomp($a);           # chomp remove newline
   chomp($a = <STDIN>); # we can combine both

e.g. Below code shows addition of two numbers, which are provided by user from the command line.

   #!/usr/bin/perl
   print “Enter first digit for Sum\n”;
   chomp($num1 = <STDIN>);

   print “Enter Second digit for Sum\n”;
   chomp($num2 = <STDIN>);

   $sum = $num1 + $num2;
   print “Sum of two digit is $sum \n”;

 

Comparison operators for numbers and strings

Comparison Operators

Numeric

String

Equal

==

eq

Not equal

!=

ne

Less than

<

lt

Greater than

>

gt

Less than or equal to

<=

le

Greater than or equal to

>=

ge

Conditional Statements

If statement

If the condition stated in side the bracket met then the code, which is written in side curly braces, get executed.      

   $x = 10;
   if ($x == 15){
      print “x is equal to 15”;
   }
   if ( ($var ne “zero") && ($var == 0)) {
      print “$var is a equal to 0\n”;
   }

 

Statement – If else

If the condition does not met then else part get executed.

   if ($x <= 10){
      print “x is less than or equal to 10”;
   }
   else{
      print “x is greater than 10”;
   }

 

If elsif else statement

In this case, if the condition does not meet the requirement then it check with next condition, which is written as elsif. And even if the elsif part does not meet the requirement then it goes to else part.

   if(($x ==9 )){
      print “x is equal to $x”;
   }
   elsif(($x == 7)){
      print “x is equal to $x”;
   }
   else{
      print ‘x is not 7 or 9’;
   }

Unless statement

It is just opposite of if statement. Here, curly bracket code executed if the condition mentioned in unless does not meet the requirement.

   unless($country eq “India”){
      print “Country is not India”;
   }

Unless else statement

   unless($Country ne “india”){
     print “Country is not India”;
   }
   else{
     print “Country is not India”;
   }

The ? : Operator

   COND ? THEN : ELSE

This is also like if else statement, wherein if the COND part meet the requirement then execute THEN part or else execute ELSE part.

e.g

   $inference= $salary_per_month >= 40000 ? "OK" : "NOT OK";
   print "\n$inference \n";

Here, if the $salary_per_month  is above 40,000 then $inference will be “OK” or else it will be “NOT OK”

PERL LOOPS

The while Statement

In while loop, execution keeps iterating through code block if the condition meet the requirement or always evaluate as true. It come out of loop once it become false.

   while(TRUE){
      # statement
   }

e.g.
   $value = 1;
   while( $value < 20 ){
       print “$value\n”;
       $value++;
   }

 

The for Statement

This loop is very similar to c program ‘for loop’, In for loop, initialization variable get initialized and this get evaluated by test expression. This loop keeps iterating until test expression become false. Here increment expression is used.

 

   for ( initial_exp ; test_exp ; re-init_exp ) {
       statement_1 ;
       statement_2 ;
       statement_3 ;
   }

e.g. In the example below $i initialized to 1, and this is evaluated in test expression. $i increment with every iteration , as the $++ executes. This loop terminates if $i become more than 5,


   for ($i = 1; $i <= 5; $i++) { 
       print $i ** 2 . “\n ";
   }

Output
  1
  4
  9
  16
  25

 

The foreach Statement

Foreach loop keeps iterating number of times, define by number of elements present in an array; every iteration returns element of an array, and its get assigned to $var variable.

    foreach $var ( list) {
       statement_1 ;
       statement_2 ;
       statement_3 ;
    }

e.g.
    foreach $num (1,5,15,25,35){
       print “$num\n”
    }

    foreach $var (1..10){
       print “$var\n”;
    }

If variable not defined then Perl automatically assign returned element to special variable $_. In this example 1..10 is used. It define the range from 1 to 10.

 

   foreach (1..10){
       print “$_\n”;   # print 1,2,3,4,5,6,7,8,9,10
   }

 

 

Control Structures

The last Statement

Last statement is a control structure, when used it disrupt loop and come out of it. You can use it with any condition . Therefore, with last if the condition meets then loop breaks.

    while ( something ) {
        something;
        if ( somecondition ) {
           statement;
           last; # break out of the while loop
        }
        morethings ;
    }

    # last comes here

 

e.g.
    while($i < 20){
        $square_root = $i **2;
        if ($square_root > 64){      # In example if $square_root goes
          last;                      # above 64 then it come out of loop.           
        }
        print "$square_root\n";
        $i++;
    }

The next Statement

    while ( something ) {
        firstpart ;
        if ( somecondition ) {
           somepart ;
           next;
        }
        otherpart ;
        # next comes here
    }
 e.g.

    while($i < 20){
        $i++;
        if ($i == 10){
           next;
        }
        print “$i\n”;
    }

 The redo Operator

It says to go back to the top of the current loop block, without testing any conditional expression or advancing to the next iteration.

    my $errors = 0;
    foreach $var ( “tango”, “bravo”, “pebbles”, “dino”, “wilma”, “betty” ) {
         ## redo comes here ##
         print "Type the word $var";
         chomp(my $try = <STDIN>);
         If ($try ne $var) {
            print "Sorry - That's not right.\n\n";
            $errors++;
            redo;
            # jump back up to the top of the loop
         }
    }
    print "You've completed the test, with $errors errors.\n"

Labeled Blocks

   LABEL_XY:
   print " I am here\n";
   while($i < 20){
       $i++;
       while($i == 10){
            goto LABEL_XY;
       }
       print "$i\n";
   }

 

Logical operator

   if(($age > 60) || ($age gt “sixty”)){
      print “You can avail senior citizen benefits”;
   }

   if(($person_age >= “18”) && ( gender eq “male”)){
      print “He is Adult male\n”;
   }

Arrays

A array or list is ordered scalar data. An array is a variable that holds a list. Each element of the array is a separate scalar variable with an independent scalar value. A array can be defined in following ways.

    (1,7,3);
    ("bret",6.5) ;
    ($c,19);
    ($a+$b,$x+$y); # sum two number can be stored as array element.


Array constructor 

    (1 .. 7)       # same as (1, 2, 3, 4, 5,6,7)
    (1.2 .. 3.2)   # same as (1.2, 2.2, 3.2)
    ($e .. $g) # list every comes between $e and $g
    (2 .. 4,13,18) # same as (2,3,4,13,18)

 

Array Variables

An array variable holds  list value (zero or more scalar values), these values called as elements. Array variable names prefixed by @ sign.

    @array_name   # this is an array variable

Assigning list to array variable

   @array_name= (1,2,3);         # The array_name gets a three-element literal
   @array_name2 = @array_name;   # now that is copied to @barney
   @array2 = (“one”, “two”);
   @bar = (4,5,@array2,6,7);     # @bar becomes (4,5,"one","two",6,7)
                           
   @barney = (8,@bar);           # puts 8 in front of @bar
   @barney = (@barney,"last");   # and a "last" at the end
                                 # @barney is now 
                                 # (8,4,5,“one","two",6,7,"last")

Quote word

Generally, we put double quote when we assign words as element to an array. That required lot of typing. And also, it looks more complex.

    @a = ("john","marry","betty","matt");  # Looks more complex 

Perl provide Quote word (qw) to make things easier. In this case we don’t have to put double or single quote.

    @a = qw(john marry betty matt); # This looks better!  


 Assigning list or array values to multiple scalar variables.
   
   ($a,$b,$c) = (1,2,3); # give 1 to $a, 2 to $b, 3 to $c  
   ($e,$f) = ($f,$e);    # swap the value of $e and $f  

 

Array Element Access

We can access an array element by numeric index. Index start from 0.

   @foo = (7,8,9);
   $b = $foo[0];
   $foo[0] = 4;     # now @foo contains (4,8,9)

Other elements can be accessed with equal ease:

   $c = $foo[1];    # give 8 to $c
   $foo[2]++;       # increment the third element of @fred
   $foo[1] += 4;    # add 4 to the second element

 

Accessing a list of elements from the same array is called a slice

   @foo=(22,32,45,77); 
   print "@foo[0,1]";             # this print 22 and 32 
                    
   @foo[0,1] = @foo[1,0];         # swap the first two elements,
                                  # i.e., 0th element become 32 and 
                                  #1st become 22

A negative subscript on an array

   @array = ("john","marry","betty","matt");
   print $array[-1];                         # prints "matt"
   print $array[-2];                         # prints "betty"

 

The push and pop functions

Push function add element in an array at the last position. In other hand,  “pop” removes last element of an array.

   push(@mylist,$newvalue);  # pushes #newvalue value in the end into @mylist 

   $oldvalue = pop(@mylist); # removes the last element of @mylist

e.g.
   @mylist = (1,2,3);

   push(@mylist,4,5,6);      # @mylist now becomes 1,2,3,4,5,6.
 

Note: that the first argument must be an array.

The shift and unshift Functions/subroutine

Unshift function add element in an array at first position, while shift remove first element of an array.

    unshift(@bar,$a);       # @bar will have value of $a at first position

    unshift(@bar,$a,$b,$c); # like @bar = ($a,$b,$c,@bar);

    $x = shift(@bar);       # remove first element of @bar and assign it to $x

e.g.
    @bar = (5,6,7);

    unshift(@bar,2,3,4); # @bar is now (2,3,4,5,6,7)

    $x = shift(@bar); # $x gets 2, @bar is now (3,4,5,6,7)

 

The reverse and sort Function

 

Reverse

This subroutine/function reverse the position of all the elements in an array.

    @a = (7,8,9);
    @b = reverse(@a); # gives @b the value of (9,8,7)
    @b = reverse(7,8,9); # same thing

Sort

This subroutine sort the element of an array in ascending order.

    @x = sort("john","matt","harry");
    print "@x";                           # output will be "harry","john","matt"

revers/descending order short

In order to do descending order sort you have to use {$b cmp $a}

    @x=("john","matt","harry");
    @rev = sort {$b cmp $a} (@x);
    print "@rev";                         # output will be "matt,"john","harry"

 

Numeric sort

For numeric sort, {$a <=> $b} has to be used

    @array_num= (4,66,3,6,22,55);
    @articles_num = sort {$a <=> $b} (@array_num);   # gets 3,4,6,22,55,66

Revers/descending order sort

    @articles_num = sort {$b <=> $a} (@array_num);   # gets 66,55,22,6,4,3

 

Next  (go to Day two tutorial)

You May Also Like..

How to do unit testing in Perl

How to do unit testing in Perl programming

How to do unit testing in Perl  : In software development life cycle Testing play very important part. If testing […]

Learn Perl programming in two days – Day two

Previous (Go to day of this Tutorial) Day Two – Learn Perl programming in two Days   Splice Splice subroutine […]

4 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *