SlideShare a Scribd company logo
1 of 55
Introduction to Perl

Part I

           By: Amit Kr. Sinha
    Nex-G Exuberant Solutions Pvt. Ltd.
What is Perl?
   Perl is a Portable Scripting Language
      No compiling is needed.
      Runs on Windows, UNIX, LINUX and cygwin



   Fast and easy text processing capability
   Fast and easy file handling capability
   Written by Larry Wall
   “Perl is the language for getting your job done.”


   Too Slow For Number Crunching
   Ideal for Prototyping
November 22, 2012
How to Access Perl

 To install at home
    Perl Comes by Default on Linux, Cygwin, MacOSX
    www.perl.com Has rpm's for Linux
    www.activestate.com Has binaries for Windows



 Latest Version is 5.8
    To check if Perl is working and the version number
       % perl -v




  November 22, 2012
Resources For Perl
 Books:
     Learning Perl
          By Larry Wall
          Published by O'Reilly
     Programming Perl
          By Larry Wall,Tom Christiansen and Jon Orwant
          Published by O'Reilly
 Web Site
     http://safari.oreilly.com
             Contains both Learning Perl and Programming Perl
              in ebook form
 November 22, 2012
Web Sources for Perl
 Web
    www.perl.com
    www.perldoc.com
    www.perl.org
    www.perlmonks.org




 November 22, 2012
The Basic Hello World Program
 which perl
 pico hello.pl
 Program:

    #! /…path…/perl -w
    print “Hello World!n”;

 Save this as “hello.pl”
 Give it executable permissions
       chmod a+x hello.pl
 Run it as follows:
       ./hello.pl

  November 22, 2012
“Hello World” Observations
   “.pl” extension is optional but is commonly used
   The first line “#!/usr/local/bin/perl” tells UNIX where
    to find Perl
   “-w” switches on warning : not required but a really
    good idea




November 22, 2012
Variables and Their Content
Numerical Literals
  Numerical Literals
         6               Integer
         12.6            Floating Point
         1e10            Scientific Notation
         6.4E-33         Scientific Notation
         4_348_348     Underscores instead of
                      commas for long numbers




November 22, 2012
String Literals
 String Literals
    “There is more than one way to do it!”
    'Just don't create a file called -rf.'
    “Beauty?nWhat's that?n”
    “”
    “Real programmers can write assembly in any
     language.”



                       Quotes from Larry Wall
  November 22, 2012
Types of Variables
 Types of variables:
    Scalar variables : $a, $b, $c
    Array variables : @array
    Hash variables : %hash
    File handles : STDIN, STDOUT, STDERR



 Variables do not need to be declared
 Variable type (int, char, ...) is decided at run time
    $a = 5;       # now an integer
       $a = “perl”;   # now a string

 November 22, 2012
Operators on Scalar Variables
  Numeric and Logic Operators
     Typical : +, -, *, /, %, ++, --, +=, -=, *=, /=, ||, &&, ! ect
      …
     Not typical: ** for exponentiation



  String Operators
     Concatenation: “.” - similar to strcat

        $first_name = “Larry”;
        $last_name = “Wall”;
        $full_name = $first_name . “ “ . $last_name;

November 22, 2012
Equality Operators for Strings
 Equality/ Inequality : eq and ne


    $language = “Perl”;
    if ($language == “Perl”) ... # Wrong!
    if ($language eq “Perl”) ... #Correct

        Use eq / ne rather than == / != for strings




  November 22, 2012
Relational Operators for Strings
 Greater than
       Numeric : >          String : gt
 Greater than or equal to
       Numeric : >=         String : ge
 Less than
       Numeric : <          String : lt
 Less than or equal to
       Numeric : <=         String : le


  November 22, 2012
String Functions
 Convert to upper case
          $name = uc($name);
 Convert only the first char to upper case
          $name = ucfirst($name);

 Convert to lower case
          $name = lc($name);
 Convert only the first char to lower case
          $name = lcfirst($name);

November 22, 2012
A String Example Program
 Convert to upper case
    $name = uc($name);
 Convert only the first char to upper case
    $name = ucfirst($name);


 Convert to lower case
    $name = lc($name);
 Convert only the first char to lower case
    $name = lcfirst($name);
    #!/usr/bin/perl
    $var1 = “larry”;
    $var2 = “moe”;
    $var3 = “shemp”;
    ……
    Output: Larry, MOE, sHEMP


   November 22, 2012
A String Example Program
 #!/usr/local/bin/perl
 $var1 = “larry”;
 $var2 = “moe”;
 $var3 = “shemp”;

 print ucfirst($var1);       # Prints 'Larry'
 print uc($var2);            # Prints 'MOE'
 print lcfirst(uc($var3));   # Prints 'sHEMP'


November 22, 2012
Variable Interpolation

 Perl looks for variables inside strings and replaces
  them with their value
           $stooge = “Larry”
           print “$stooge is one of the three stooges.n”;
    Produces the output:
           Larry is one of the three stooges.
 This does not happen when you use single quotes
           print '$stooge is one of the three stooges.n’;
    Produces the output:
           $stooge is one of the three stooges.n
 November 22, 2012
Character Interpolation
 List of character escapes that are recognized
     when using double quoted strings
          n       newline
          t       tab
          r       carriage return

 Common Example :


          print “Hellon”; # prints Hello and then a return
November 22, 2012
Numbers and Strings are
    Interchangeable
 If a scalar variable looks like a number and Perl
  needs a number, it will use it as a number

    $a = 4;             # a number
    print $a + 18; #   prints 22
    $b = “50”;     #   looks like a string, but ...
    print $b – 10;      # will print 40!



  November 22, 2012
Control Structures: Loops and Conditions
If ... else ... statements

  if ( $weather eq “Rain” )
     {
      print “Umbrella!n”;
     }
  elsif ( $weather eq “Sun” ) {
      print “Sunglasses!n”;
  }
  else {
      print “Anti Radiation Armor!n”;
  }
November 22, 2012
Unless ... else Statements
 Unless Statements are the opposite of if ... else
  statements.

   unless ($weather eq “Rain”) {
        print “Dress as you wish!n”;
   }
   else {
        print “Umbrella!n”;
   }

 And again remember the braces are required!
  November 22, 2012
While Loop
 Example :
   $i = 0;
   while ( $i <= 1000 )
      {
      print “$in”;
      $i++;
   }




  November 22, 2012
Until Loop
 The until function evaluates an expression
  repeatedly until a specific condition is met.

 Example:
         $i = 0;
         until ($i == 1000) {
           print “$in”;
            $i++;
         }
  November 22, 2012
For Loops
     Syntax 1:
        for ( $i = 0; $i <= 1000; $i=$i+2 )

         {
            print “$in”;
         }

     Syntax 2:
        for $i(0..1000)

         {
            print “$in”;
         }

November 22, 2012
Moving around in a Loop
 next: ignore the current iteration
 last: terminates the loop.


 What is the output for the following code snippet:
   for ( $i = 0; $i < 10; $i++)
       {
             if ($i == 1 || $i == 3) { next; }
             elsif($i == 5) { last; }
             else
                    {print “$in”;}
       }
  November 22, 2012
Answer



         0
         2
         4
Exercise
 Use a loop structure and code a program that
  produces the following output:

        A
        AA
        AAA
        AAAB
        AAABA
        AAABAA
        AAABAAA
        AAABAAAB
        …..

  November 22, 2012
   TIP: $chain = $chain . “A”;
Exercise
 #! /usr/bin/perl

      for ($i=0, $j=0; $i<100; $i++)
          {
             if ( $j==3){$chain.=“B”;$j=0;}
             else {$chain.=“A”; $j++;}
             print “$chainn”;
          }


November 22, 2012
Exercise: Generating a Random
   Sample
 A study yields an outcome between 0 and 100
  for every patient. You want to generate an
  artificial random study for 100 patients:

    Patient 1 99
    Patient 2 65
    Patient 3 89
    ….

   Tip:
       - use the srand to seed the random number
       generator
       -use rand 100 to generate values between 0 and
       100 :
  November 22, 2012 rand 100
Exercise

 for ($i=0; $i<100; $i++)
   {
   $v=rand 100;
   #print “Patient $i $vn”;
   printf “Patient %d %.2fnn”, $i, $v;
   #%s : chaines, strings
   #%d : integer
   #%f : floating points
   }
November 22, 2012
Collections Of Variables: Arrays
Arrays
 Array variable is denoted by the @ symbol
   @array = ( “Larry”, “Curly”, “Moe” );


 To access the whole array, use the whole
  array
       print @array; # prints : Larry Curly Moe

              Notice that you do not need to loop through
               the whole array to print it – Perl does this for
               you
 November 22, 2012
Arrays cont…
 Array Indexes start at 0 !!!!!

 To access one element of the array : use $
    Why? Because every element in the array is scalar


          print “$array[0]n”; # prints : Larry

 Question:

          What happens if we access $array[3] ?

              
November 22, 2012
                    Answer1 : Value is set to 0 in Perl
                   Answer2: Anything in C!!!!!
Arrays cont ...

 To find the index of the last element in the
   array
     print $#array; # prints 2 in the previous
                   # example

 Note another way to find the number of
   elements in the array:
     $array_size = @array;
      $array_size now has 3 in the above example
       because there are 3 elements in the array
 November 22, 2012
Sorting Arrays
 Perl has a built in sort function
 Two ways to sort:
       Default : sorts in a standard string comparisons order
           sort LIST

       Usersub: create your own subroutine that returns an
        integer less than, equal to or greater than 0
           Sort USERSUB LIST

           The <=> and cmp operators make creating sorting

            subroutines very easy



  November 22, 2012
Numerical Sorting Example
#!/usr/local/bin/perl -w
@unsortedArray = (3, 10, 76, 23, 1, 54);
@sortedArray = sort numeric @unsortedArray;

print “@unsortedArrayn”; # prints 3 10 76 23 1 54
print “@sortedArrayn”; # prints 1 3 10 23 54 76

sub numeric
  {
   return $a <=> $b;

   }
# Numbers: $a <=> $b :    -1 if $a<$b , 0 if $a== $b, 1 if $a>$b
# Strings: $a cpm $b :    -1 if $a<$b , 0 if $a== $b, 1 if $a>$b
November 22, 2012
String Sorting Example
 #!/usr/local/bin/perl -w
 @unsortedArray = (“Larry”, “Curly”, “moe”);
 @sortedArray = sort { lc($a) cmp lc($b)} @unsortedArray;


 print “@unsortedArrayn”; # prints Larry Curly moe
 print “@sortedArrayn”;      # prints Curly Larry moe




 November 22, 2012
Foreach
 Foreach allows you to iterate over an array
 Example:
   foreach $element (@array)
   {
     print “$elementn”;
   }

 This is similar to :
    for ($i = 0; $i <= $#array; $i++)
    {
        print “$array[$i]n”;
    }
  November 22, 2012
Sorting with Foreach
 The sort function sorts the array and returns the list in
  sorted order.
 Example :
                     @array( “Larry”, “Curly”, “Moe”);
                     foreach $element (sort @array)
                          {
                          print “$element ”;
                          }

 Prints the elements in sorted order:
                     Curly Larry Moe
 November 22, 2012
Exercise: Sorting According to
      Multiple Criterion
   Use the following initialization to sort individuals by age and then by
    income:

   Syntax

     @sortedArray = sort numeric @unsortedArray;
     sub numeric
        {
            return $a <=> $b;
        }
     Data

          @index=(0,1,2,3,4);
          @name=(“V”,“W”,”X”,”Y”,”Z”);
          @age=(10,20, 15, 20, 10);
          @income=(100,670, 280,800,400);

   Output:
          Name X Age A Income I
          …

     Tip:
    November 22, 2012
        -Sort the index, using information contained in the other arrays.
Exercise: Sorting According to
      Multiple Criterion

    @index=(0,1,2,3,4,5);
    @name=(“V”,“W”,”X”,”Y”,”Z”);
    @age=(10,20, 15, 20, 10);
    @income=(100,670, 280,800,400);

    foreach $i ( sort my_numeric @index)
         {
               print “$name[$i] $age[$i] $income[$i];
         }
    sub my_numeric
        {
          if ($age[$a] == $age[$b])
               {return $income[$a]<=>$income[$b]; }
         else
                   {return $age[$a]<=>$age[$b]; }
        }
    November 22, 2012
Manipulating Arrays
Strings to Arrays : split
 Split a string into words and put into an array
   @array = split( /;/, “Larry;Curly;Moe” );
   @array= (“Larry”, “Curly”, “Moe”);
        # creates the same array as we saw   previously

 Split into characters
   @stooge = split( //, “curly” );
   # array @stooge has 5 elements: c, u, r, l, y




   November 22, 2012
Split cont..
 Split on any character
   @array = split( /:/, “10:20:30:40”);
   # array has 4 elements : 10, 20, 30, 40

 Split on Multiple White Space
   @array = split(/s+/, “this is a test”;
   # array has 4 elements : this, is, a, test

                   More on ‘s+’ later



November 22, 2012
Arrays to Strings
 Array to space separated string
   @array = (“Larry”, “Curly”, “Moe”);
   $string = join( “;“, @array);
     # string = “Larry;Curly;Moe”

 Array of characters to string
   @stooge = (“c”, “u”, “r”, “l”, “y”);
   $string = join( “”, @stooge );
     # string = “curly”



November 22, 2012
Joining Arrays cont…
 Join with any character you want
   @array = ( “10”, “20”, “30”, “40” );
   $string = join( “:”, @array);
     # string = “10:20:30:40”

 Join with multiple characters
   @array = “10”, “20”, “30”, “40”);
   $string = join(“->”, @array);
     # string = “10->20->30->40”



November 22, 2012
Arrays as Stacks and Lists
 To append to the end of an array :
   @array = ( “Larry”, “Curly”, “Moe” );
   push (@array, “Shemp” );
   print $array[3];   # prints “Shemp”

 To remove the last element of the array (LIFO)
   $elment = pop @array;
   print $element; # prints “Shemp”
    @array now has the original elements

             (“Larry”, “Curly”, “Moe”)

November 22, 2012
Arrays as Stacks and Lists

 To prepend to the beginning of an array
   @array = ( “Larry”, “Curly”, “Moe” );
   unshift @array, “Shemp”;
   print $array[3]; # prints “Moe”
   print “$array[0]; # prints “Shemp”

 To remove the first element of the array
   $element = shift @array;
   print $element; # prints “Shemp”
    The array now contains only :
 November 22, 2012
       “Larry”, “Curly”, “Moe”
Exercise: Spliting
 Instructions
    Remove
             shift: beginning, pop: end
       Add
             Unshift: beginning, push: end


 Use split, shift and push to turn the following string:

   “The enquiry 1 was administered to five couples”
   “The enquiry 2 was administered to six couples”
   “The enquiry 3 was administered to eigh couples”

  Into
   “five couples were administered the enquiry 1”
  ….
  November 22, 2012
Exercise: Spliting
 Use split, shift and push to turn the following string:

  $s[0]= “The enquiry 1 was administered to five couples”;
  $s[1]= “The enquiry 2 was administered to six couples”;
  $s[2]= “The enquiry 3 was administered to eigh couples”;
  foreach $s(@s)
       {
       @s2=split (/was administered to/, $s);
       $new_s=“$s2[1] were admimistered $s2[0]”;
       print “$new_sn”;
      }




  November 22, 2012
Multidimentional Arrays
Multi Dimensional Arrays
 Better use Hash tables (cf later)
 If you need to:
       @tab=([‘Monday’,’Tuesday’],
               [‘Morning’,’Afternoon’,’Evening’]);
      $a=$tab[0][0] # $a == ‘Monday’
      $tab2=(‘midnight’, ‘Twelve’);
      $tab[2]=@tab2 # integrate tab2 as the last row
        of tab


November 22, 2012
Thank you 

More Related Content

What's hot

Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Bozhidar Boshnakov
 
Practical approach to perl day1
Practical approach to perl day1Practical approach to perl day1
Practical approach to perl day1Rakesh Mukundan
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about LambdasRyan Knight
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHPAhmed Swilam
 
Scripting3
Scripting3Scripting3
Scripting3Nao Dara
 
Introduction to pygments
Introduction to pygmentsIntroduction to pygments
Introduction to pygmentsroskakori
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...Fwdays
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP FunctionsAhmed Swilam
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpMichael Girouard
 
PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2Kumar
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developersjessitron
 
Contracts in-clojure-pete
Contracts in-clojure-peteContracts in-clojure-pete
Contracts in-clojure-petejessitron
 
Php Chapter 2 3 Training
Php Chapter 2 3 TrainingPhp Chapter 2 3 Training
Php Chapter 2 3 TrainingChris Chubb
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsMark Baker
 

What's hot (18)

Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
 
Practical approach to perl day1
Practical approach to perl day1Practical approach to perl day1
Practical approach to perl day1
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about Lambdas
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
Scripting3
Scripting3Scripting3
Scripting3
 
Introduction to pygments
Introduction to pygmentsIntroduction to pygments
Introduction to pygments
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
 
PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developers
 
Contracts in-clojure-pete
Contracts in-clojure-peteContracts in-clojure-pete
Contracts in-clojure-pete
 
Php Chapter 2 3 Training
Php Chapter 2 3 TrainingPhp Chapter 2 3 Training
Php Chapter 2 3 Training
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
OOP
OOPOOP
OOP
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 

Similar to Introduction to Perl Programming

Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 
Perl 5.10
Perl 5.10Perl 5.10
Perl 5.10acme
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Kang-min Liu
 
Perl training-in-navi mumbai
Perl training-in-navi mumbaiPerl training-in-navi mumbai
Perl training-in-navi mumbaivibrantuser
 
Lecture 23
Lecture 23Lecture 23
Lecture 23rhshriva
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In PerlKang-min Liu
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perlworr1244
 
Perl6 for-beginners
Perl6 for-beginnersPerl6 for-beginners
Perl6 for-beginnersJens Rehsack
 
Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent. Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent. Workhorse Computing
 

Similar to Introduction to Perl Programming (20)

Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Perl basics for Pentesters
Perl basics for PentestersPerl basics for Pentesters
Perl basics for Pentesters
 
PHP-01-Overview.ppt
PHP-01-Overview.pptPHP-01-Overview.ppt
PHP-01-Overview.ppt
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Perl 5.10
Perl 5.10Perl 5.10
Perl 5.10
 
groovy & grails - lecture 2
groovy & grails - lecture 2groovy & grails - lecture 2
groovy & grails - lecture 2
 
PERL.ppt
PERL.pptPERL.ppt
PERL.ppt
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
PHP_Lecture.pdf
PHP_Lecture.pdfPHP_Lecture.pdf
PHP_Lecture.pdf
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
 
Perl training-in-navi mumbai
Perl training-in-navi mumbaiPerl training-in-navi mumbai
Perl training-in-navi mumbai
 
PHP-Overview.ppt
PHP-Overview.pptPHP-Overview.ppt
PHP-Overview.ppt
 
Perl
PerlPerl
Perl
 
Lecture 23
Lecture 23Lecture 23
Lecture 23
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Perl6 for-beginners
Perl6 for-beginnersPerl6 for-beginners
Perl6 for-beginners
 
Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent. Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
 

Recently uploaded

Dubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home MadeDubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home Madekojalkojal131
 
Top Rated Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...
Top Rated  Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...Top Rated  Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...
Top Rated Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...Call Girls in Nagpur High Profile
 
Delhi Call Girls Patparganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Patparganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Patparganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Patparganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Personal Brand Exploration - Fernando Negron
Personal Brand Exploration - Fernando NegronPersonal Brand Exploration - Fernando Negron
Personal Brand Exploration - Fernando Negronnegronf24
 
Delhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Experience Certificate - Marketing Analyst-Soham Mondal.pdf
Experience Certificate - Marketing Analyst-Soham Mondal.pdfExperience Certificate - Marketing Analyst-Soham Mondal.pdf
Experience Certificate - Marketing Analyst-Soham Mondal.pdfSoham Mondal
 
女王大学硕士毕业证成绩单(加急办理)认证海外毕业证
女王大学硕士毕业证成绩单(加急办理)认证海外毕业证女王大学硕士毕业证成绩单(加急办理)认证海外毕业证
女王大学硕士毕业证成绩单(加急办理)认证海外毕业证obuhobo
 
Book Paid Saswad Call Girls Pune 8250192130Low Budget Full Independent High P...
Book Paid Saswad Call Girls Pune 8250192130Low Budget Full Independent High P...Book Paid Saswad Call Girls Pune 8250192130Low Budget Full Independent High P...
Book Paid Saswad Call Girls Pune 8250192130Low Budget Full Independent High P...ranjana rawat
 
CALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual serviceanilsa9823
 
Dark Dubai Call Girls O525547819 Skin Call Girls Dubai
Dark Dubai Call Girls O525547819 Skin Call Girls DubaiDark Dubai Call Girls O525547819 Skin Call Girls Dubai
Dark Dubai Call Girls O525547819 Skin Call Girls Dubaikojalkojal131
 
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...shivangimorya083
 
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...shivangimorya083
 
Résumé (2 pager - 12 ft standard syntax)
Résumé (2 pager -  12 ft standard syntax)Résumé (2 pager -  12 ft standard syntax)
Résumé (2 pager - 12 ft standard syntax)Soham Mondal
 
Resumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying OnlineResumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying OnlineBruce Bennett
 
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...amitlee9823
 
Production Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjProduction Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjLewisJB
 
Zeeman Effect normal and Anomalous zeeman effect
Zeeman Effect normal and Anomalous zeeman effectZeeman Effect normal and Anomalous zeeman effect
Zeeman Effect normal and Anomalous zeeman effectPriyanshuRawat56
 
Dubai Call Girls Starlet O525547819 Call Girls Dubai Showen Dating
Dubai Call Girls Starlet O525547819 Call Girls Dubai Showen DatingDubai Call Girls Starlet O525547819 Call Girls Dubai Showen Dating
Dubai Call Girls Starlet O525547819 Call Girls Dubai Showen Datingkojalkojal131
 
Motilal Oswal Gift City Fund PPT - Apr 2024.pptx
Motilal Oswal Gift City Fund PPT - Apr 2024.pptxMotilal Oswal Gift City Fund PPT - Apr 2024.pptx
Motilal Oswal Gift City Fund PPT - Apr 2024.pptxMaulikVasani1
 

Recently uploaded (20)

Dubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home MadeDubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
Dubai Call Girls Naija O525547819 Call Girls In Dubai Home Made
 
Top Rated Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...
Top Rated  Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...Top Rated  Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...
Top Rated Pune Call Girls Deccan ⟟ 6297143586 ⟟ Call Me For Genuine Sex Serv...
 
Delhi Call Girls Patparganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Patparganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Patparganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Patparganj 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Personal Brand Exploration - Fernando Negron
Personal Brand Exploration - Fernando NegronPersonal Brand Exploration - Fernando Negron
Personal Brand Exploration - Fernando Negron
 
Delhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls South Delhi 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Experience Certificate - Marketing Analyst-Soham Mondal.pdf
Experience Certificate - Marketing Analyst-Soham Mondal.pdfExperience Certificate - Marketing Analyst-Soham Mondal.pdf
Experience Certificate - Marketing Analyst-Soham Mondal.pdf
 
女王大学硕士毕业证成绩单(加急办理)认证海外毕业证
女王大学硕士毕业证成绩单(加急办理)认证海外毕业证女王大学硕士毕业证成绩单(加急办理)认证海外毕业证
女王大学硕士毕业证成绩单(加急办理)认证海外毕业证
 
Book Paid Saswad Call Girls Pune 8250192130Low Budget Full Independent High P...
Book Paid Saswad Call Girls Pune 8250192130Low Budget Full Independent High P...Book Paid Saswad Call Girls Pune 8250192130Low Budget Full Independent High P...
Book Paid Saswad Call Girls Pune 8250192130Low Budget Full Independent High P...
 
CALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Nishatganj Lucknow best sexual service
 
VVVIP Call Girls In East Of Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In East Of Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...VVVIP Call Girls In East Of Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In East Of Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
 
Dark Dubai Call Girls O525547819 Skin Call Girls Dubai
Dark Dubai Call Girls O525547819 Skin Call Girls DubaiDark Dubai Call Girls O525547819 Skin Call Girls Dubai
Dark Dubai Call Girls O525547819 Skin Call Girls Dubai
 
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
Delhi Call Girls Preet Vihar 9711199171 ☎✔👌✔ Whatsapp Body to body massage wi...
 
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...Vip  Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
Vip Modals Call Girls (Delhi) Rohini 9711199171✔️ Full night Service for one...
 
Résumé (2 pager - 12 ft standard syntax)
Résumé (2 pager -  12 ft standard syntax)Résumé (2 pager -  12 ft standard syntax)
Résumé (2 pager - 12 ft standard syntax)
 
Resumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying OnlineResumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying Online
 
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
 
Production Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbjProduction Day 1.pptxjvjbvbcbcb bj bvcbj
Production Day 1.pptxjvjbvbcbcb bj bvcbj
 
Zeeman Effect normal and Anomalous zeeman effect
Zeeman Effect normal and Anomalous zeeman effectZeeman Effect normal and Anomalous zeeman effect
Zeeman Effect normal and Anomalous zeeman effect
 
Dubai Call Girls Starlet O525547819 Call Girls Dubai Showen Dating
Dubai Call Girls Starlet O525547819 Call Girls Dubai Showen DatingDubai Call Girls Starlet O525547819 Call Girls Dubai Showen Dating
Dubai Call Girls Starlet O525547819 Call Girls Dubai Showen Dating
 
Motilal Oswal Gift City Fund PPT - Apr 2024.pptx
Motilal Oswal Gift City Fund PPT - Apr 2024.pptxMotilal Oswal Gift City Fund PPT - Apr 2024.pptx
Motilal Oswal Gift City Fund PPT - Apr 2024.pptx
 

Introduction to Perl Programming

  • 1. Introduction to Perl Part I By: Amit Kr. Sinha Nex-G Exuberant Solutions Pvt. Ltd.
  • 2. What is Perl?  Perl is a Portable Scripting Language  No compiling is needed.  Runs on Windows, UNIX, LINUX and cygwin  Fast and easy text processing capability  Fast and easy file handling capability  Written by Larry Wall  “Perl is the language for getting your job done.”  Too Slow For Number Crunching  Ideal for Prototyping November 22, 2012
  • 3. How to Access Perl  To install at home  Perl Comes by Default on Linux, Cygwin, MacOSX  www.perl.com Has rpm's for Linux  www.activestate.com Has binaries for Windows  Latest Version is 5.8  To check if Perl is working and the version number  % perl -v November 22, 2012
  • 4. Resources For Perl  Books:  Learning Perl  By Larry Wall  Published by O'Reilly  Programming Perl  By Larry Wall,Tom Christiansen and Jon Orwant  Published by O'Reilly  Web Site  http://safari.oreilly.com  Contains both Learning Perl and Programming Perl in ebook form November 22, 2012
  • 5. Web Sources for Perl  Web  www.perl.com  www.perldoc.com  www.perl.org  www.perlmonks.org November 22, 2012
  • 6. The Basic Hello World Program  which perl  pico hello.pl  Program: #! /…path…/perl -w print “Hello World!n”;  Save this as “hello.pl”  Give it executable permissions  chmod a+x hello.pl  Run it as follows:  ./hello.pl November 22, 2012
  • 7. “Hello World” Observations  “.pl” extension is optional but is commonly used  The first line “#!/usr/local/bin/perl” tells UNIX where to find Perl  “-w” switches on warning : not required but a really good idea November 22, 2012
  • 9. Numerical Literals  Numerical Literals  6 Integer  12.6 Floating Point  1e10 Scientific Notation  6.4E-33 Scientific Notation  4_348_348 Underscores instead of commas for long numbers November 22, 2012
  • 10. String Literals  String Literals  “There is more than one way to do it!”  'Just don't create a file called -rf.'  “Beauty?nWhat's that?n”  “”  “Real programmers can write assembly in any language.”  Quotes from Larry Wall November 22, 2012
  • 11. Types of Variables  Types of variables:  Scalar variables : $a, $b, $c  Array variables : @array  Hash variables : %hash  File handles : STDIN, STDOUT, STDERR  Variables do not need to be declared  Variable type (int, char, ...) is decided at run time  $a = 5; # now an integer  $a = “perl”; # now a string November 22, 2012
  • 12. Operators on Scalar Variables  Numeric and Logic Operators  Typical : +, -, *, /, %, ++, --, +=, -=, *=, /=, ||, &&, ! ect …  Not typical: ** for exponentiation  String Operators  Concatenation: “.” - similar to strcat $first_name = “Larry”; $last_name = “Wall”; $full_name = $first_name . “ “ . $last_name; November 22, 2012
  • 13. Equality Operators for Strings  Equality/ Inequality : eq and ne $language = “Perl”; if ($language == “Perl”) ... # Wrong! if ($language eq “Perl”) ... #Correct  Use eq / ne rather than == / != for strings November 22, 2012
  • 14. Relational Operators for Strings  Greater than  Numeric : > String : gt  Greater than or equal to  Numeric : >= String : ge  Less than  Numeric : < String : lt  Less than or equal to  Numeric : <= String : le November 22, 2012
  • 15. String Functions  Convert to upper case  $name = uc($name);  Convert only the first char to upper case  $name = ucfirst($name);  Convert to lower case  $name = lc($name);  Convert only the first char to lower case  $name = lcfirst($name); November 22, 2012
  • 16. A String Example Program  Convert to upper case $name = uc($name);  Convert only the first char to upper case  $name = ucfirst($name);  Convert to lower case $name = lc($name);  Convert only the first char to lower case  $name = lcfirst($name); #!/usr/bin/perl $var1 = “larry”; $var2 = “moe”; $var3 = “shemp”; …… Output: Larry, MOE, sHEMP November 22, 2012
  • 17. A String Example Program #!/usr/local/bin/perl $var1 = “larry”; $var2 = “moe”; $var3 = “shemp”; print ucfirst($var1); # Prints 'Larry' print uc($var2); # Prints 'MOE' print lcfirst(uc($var3)); # Prints 'sHEMP' November 22, 2012
  • 18. Variable Interpolation  Perl looks for variables inside strings and replaces them with their value $stooge = “Larry” print “$stooge is one of the three stooges.n”; Produces the output: Larry is one of the three stooges.  This does not happen when you use single quotes print '$stooge is one of the three stooges.n’; Produces the output: $stooge is one of the three stooges.n November 22, 2012
  • 19. Character Interpolation  List of character escapes that are recognized when using double quoted strings  n newline  t tab  r carriage return  Common Example :  print “Hellon”; # prints Hello and then a return November 22, 2012
  • 20. Numbers and Strings are Interchangeable  If a scalar variable looks like a number and Perl needs a number, it will use it as a number $a = 4; # a number print $a + 18; # prints 22 $b = “50”; # looks like a string, but ... print $b – 10; # will print 40! November 22, 2012
  • 21. Control Structures: Loops and Conditions
  • 22. If ... else ... statements if ( $weather eq “Rain” ) { print “Umbrella!n”; } elsif ( $weather eq “Sun” ) { print “Sunglasses!n”; } else { print “Anti Radiation Armor!n”; } November 22, 2012
  • 23. Unless ... else Statements  Unless Statements are the opposite of if ... else statements. unless ($weather eq “Rain”) { print “Dress as you wish!n”; } else { print “Umbrella!n”; }  And again remember the braces are required! November 22, 2012
  • 24. While Loop  Example : $i = 0; while ( $i <= 1000 ) { print “$in”; $i++; } November 22, 2012
  • 25. Until Loop  The until function evaluates an expression repeatedly until a specific condition is met.  Example: $i = 0; until ($i == 1000) { print “$in”; $i++; } November 22, 2012
  • 26. For Loops  Syntax 1:  for ( $i = 0; $i <= 1000; $i=$i+2 ) { print “$in”; }  Syntax 2:  for $i(0..1000) { print “$in”; } November 22, 2012
  • 27. Moving around in a Loop  next: ignore the current iteration  last: terminates the loop.  What is the output for the following code snippet: for ( $i = 0; $i < 10; $i++) { if ($i == 1 || $i == 3) { next; } elsif($i == 5) { last; } else {print “$in”;} } November 22, 2012
  • 28. Answer 0 2 4
  • 29. Exercise  Use a loop structure and code a program that produces the following output: A AA AAA AAAB AAABA AAABAA AAABAAA AAABAAAB ….. November 22, 2012 TIP: $chain = $chain . “A”;
  • 30. Exercise #! /usr/bin/perl for ($i=0, $j=0; $i<100; $i++) { if ( $j==3){$chain.=“B”;$j=0;} else {$chain.=“A”; $j++;} print “$chainn”; } November 22, 2012
  • 31. Exercise: Generating a Random Sample  A study yields an outcome between 0 and 100 for every patient. You want to generate an artificial random study for 100 patients: Patient 1 99 Patient 2 65 Patient 3 89 …. Tip: - use the srand to seed the random number generator -use rand 100 to generate values between 0 and 100 : November 22, 2012 rand 100
  • 32. Exercise for ($i=0; $i<100; $i++) { $v=rand 100; #print “Patient $i $vn”; printf “Patient %d %.2fnn”, $i, $v; #%s : chaines, strings #%d : integer #%f : floating points } November 22, 2012
  • 34. Arrays  Array variable is denoted by the @ symbol  @array = ( “Larry”, “Curly”, “Moe” );  To access the whole array, use the whole array  print @array; # prints : Larry Curly Moe  Notice that you do not need to loop through the whole array to print it – Perl does this for you November 22, 2012
  • 35. Arrays cont…  Array Indexes start at 0 !!!!!  To access one element of the array : use $  Why? Because every element in the array is scalar  print “$array[0]n”; # prints : Larry  Question:  What happens if we access $array[3] ?  November 22, 2012 Answer1 : Value is set to 0 in Perl  Answer2: Anything in C!!!!!
  • 36. Arrays cont ...  To find the index of the last element in the array print $#array; # prints 2 in the previous # example  Note another way to find the number of elements in the array: $array_size = @array;  $array_size now has 3 in the above example because there are 3 elements in the array November 22, 2012
  • 37. Sorting Arrays  Perl has a built in sort function  Two ways to sort:  Default : sorts in a standard string comparisons order  sort LIST  Usersub: create your own subroutine that returns an integer less than, equal to or greater than 0  Sort USERSUB LIST  The <=> and cmp operators make creating sorting subroutines very easy November 22, 2012
  • 38. Numerical Sorting Example #!/usr/local/bin/perl -w @unsortedArray = (3, 10, 76, 23, 1, 54); @sortedArray = sort numeric @unsortedArray; print “@unsortedArrayn”; # prints 3 10 76 23 1 54 print “@sortedArrayn”; # prints 1 3 10 23 54 76 sub numeric { return $a <=> $b; } # Numbers: $a <=> $b : -1 if $a<$b , 0 if $a== $b, 1 if $a>$b # Strings: $a cpm $b : -1 if $a<$b , 0 if $a== $b, 1 if $a>$b November 22, 2012
  • 39. String Sorting Example #!/usr/local/bin/perl -w @unsortedArray = (“Larry”, “Curly”, “moe”); @sortedArray = sort { lc($a) cmp lc($b)} @unsortedArray; print “@unsortedArrayn”; # prints Larry Curly moe print “@sortedArrayn”; # prints Curly Larry moe November 22, 2012
  • 40. Foreach  Foreach allows you to iterate over an array  Example: foreach $element (@array) { print “$elementn”; }  This is similar to : for ($i = 0; $i <= $#array; $i++) { print “$array[$i]n”; } November 22, 2012
  • 41. Sorting with Foreach  The sort function sorts the array and returns the list in sorted order.  Example : @array( “Larry”, “Curly”, “Moe”); foreach $element (sort @array) { print “$element ”; }  Prints the elements in sorted order: Curly Larry Moe November 22, 2012
  • 42. Exercise: Sorting According to Multiple Criterion  Use the following initialization to sort individuals by age and then by income:  Syntax @sortedArray = sort numeric @unsortedArray; sub numeric { return $a <=> $b; } Data @index=(0,1,2,3,4); @name=(“V”,“W”,”X”,”Y”,”Z”); @age=(10,20, 15, 20, 10); @income=(100,670, 280,800,400);  Output: Name X Age A Income I … Tip: November 22, 2012 -Sort the index, using information contained in the other arrays.
  • 43. Exercise: Sorting According to Multiple Criterion  @index=(0,1,2,3,4,5); @name=(“V”,“W”,”X”,”Y”,”Z”); @age=(10,20, 15, 20, 10); @income=(100,670, 280,800,400); foreach $i ( sort my_numeric @index) { print “$name[$i] $age[$i] $income[$i]; } sub my_numeric { if ($age[$a] == $age[$b]) {return $income[$a]<=>$income[$b]; } else {return $age[$a]<=>$age[$b]; } } November 22, 2012
  • 45. Strings to Arrays : split  Split a string into words and put into an array @array = split( /;/, “Larry;Curly;Moe” ); @array= (“Larry”, “Curly”, “Moe”); # creates the same array as we saw previously  Split into characters @stooge = split( //, “curly” ); # array @stooge has 5 elements: c, u, r, l, y November 22, 2012
  • 46. Split cont..  Split on any character @array = split( /:/, “10:20:30:40”); # array has 4 elements : 10, 20, 30, 40  Split on Multiple White Space @array = split(/s+/, “this is a test”; # array has 4 elements : this, is, a, test  More on ‘s+’ later November 22, 2012
  • 47. Arrays to Strings  Array to space separated string @array = (“Larry”, “Curly”, “Moe”); $string = join( “;“, @array); # string = “Larry;Curly;Moe”  Array of characters to string @stooge = (“c”, “u”, “r”, “l”, “y”); $string = join( “”, @stooge ); # string = “curly” November 22, 2012
  • 48. Joining Arrays cont…  Join with any character you want @array = ( “10”, “20”, “30”, “40” ); $string = join( “:”, @array); # string = “10:20:30:40”  Join with multiple characters @array = “10”, “20”, “30”, “40”); $string = join(“->”, @array); # string = “10->20->30->40” November 22, 2012
  • 49. Arrays as Stacks and Lists  To append to the end of an array : @array = ( “Larry”, “Curly”, “Moe” ); push (@array, “Shemp” ); print $array[3]; # prints “Shemp”  To remove the last element of the array (LIFO) $elment = pop @array; print $element; # prints “Shemp”  @array now has the original elements (“Larry”, “Curly”, “Moe”) November 22, 2012
  • 50. Arrays as Stacks and Lists  To prepend to the beginning of an array @array = ( “Larry”, “Curly”, “Moe” ); unshift @array, “Shemp”; print $array[3]; # prints “Moe” print “$array[0]; # prints “Shemp”  To remove the first element of the array $element = shift @array; print $element; # prints “Shemp”  The array now contains only : November 22, 2012  “Larry”, “Curly”, “Moe”
  • 51. Exercise: Spliting  Instructions  Remove  shift: beginning, pop: end  Add  Unshift: beginning, push: end  Use split, shift and push to turn the following string: “The enquiry 1 was administered to five couples” “The enquiry 2 was administered to six couples” “The enquiry 3 was administered to eigh couples” Into “five couples were administered the enquiry 1” …. November 22, 2012
  • 52. Exercise: Spliting  Use split, shift and push to turn the following string: $s[0]= “The enquiry 1 was administered to five couples”; $s[1]= “The enquiry 2 was administered to six couples”; $s[2]= “The enquiry 3 was administered to eigh couples”; foreach $s(@s) { @s2=split (/was administered to/, $s); $new_s=“$s2[1] were admimistered $s2[0]”; print “$new_sn”; } November 22, 2012
  • 54. Multi Dimensional Arrays  Better use Hash tables (cf later)  If you need to:  @tab=([‘Monday’,’Tuesday’], [‘Morning’,’Afternoon’,’Evening’]); $a=$tab[0][0] # $a == ‘Monday’ $tab2=(‘midnight’, ‘Twelve’); $tab[2]=@tab2 # integrate tab2 as the last row of tab November 22, 2012