SlideShare a Scribd company logo
1 of 27
Basic Perl programming
Agenda
                             Perl introduction
                             Variables
                             Control Structures
                             Loops
                             Defining and using subroutines
                             Regular Expression
                             Using Boolean (True/False)
                             File handling



         August 2, 2012                                    2
Perl Introduction
• Perl is a general-purpose programming language
  originally developed for text manipulation. Now, Perl
  used for web development, system administration,
  network programming, core generation and more.
• Open Source and free licencing.
• Support both procedural and OOP.
• Excellent text handling and regular expressions




              August 2, 2012                              3
Installation Perl
•   Install ActivePerl 5.14.2
•   Install Eclispse 3.6 or greater
•   In Eclipse IDE go to menu item “Help > Install New Software…” to install
    EPIC plugins of Perl at link: http://e-p-i-c.sf.net/updates/testing

•   After finish installed Perl plugins, go to menu “Run -> External Tools ->
    External Tools... “ to add and active the configuration for running Perl




                      August 2, 2012                                            4
Variables
Scalar:
  $myString         = “Hello” ;  hello
  $num1      =    10.5;   10.5
  $num2 = $num1;          10.5
  print “Number is :$num1”;    Number is :10.5
  Prefix characters on Perl:
  • $: variable containing scalar values such as a number or a string
  • @: variable containing a list with numeric keys
  • %: variable containing a list with strings as keys
  • &: subroutine
  • *: matches all structures with the associated name


                    August 2, 2012                                      5
Variables
Array (1):
  @colors = (“Red”, “Blue”, “Orange”);
    $colors[0] = “Red”;
    $colors[1] = “Blue”;
    $colors[2] = “Orange”;
  print “Our colors variable contains: @ colors ”;
            Our colors variable contains : Red Blue Orange
  print “First element of the colors is: $colors[0]”;
            First element of the colors is: Red
  @CombinedArray =(@Array1,@Array2);// merge 2
  arrays
  @hundrednums = (101 .. 200);



               August 2, 2012                                 6
Variables
Array (2):
  Perl functions for working with arrays:
   •   pop - remove last element of an array:
   •   push - add an element to the end of array;
   •   shift - removes first element of an array;
   •   unshift - add an element to the beginning of array;
   •   sort - sort an array.
  EG:
  @colors = (“Red”, “Blue”, “Orange”);
  print “Our colors variable contains: @ colors ”;
              Our colors variable contains : Red Blue Orange
  pop @colors;
  print “Colors after applying pop function:
  @array1[0..$#array1]";
              Colors after applying pop function: Red Blue

                      August 2, 2012                            7
Variables
Hashes:
- %name_email = ("John", "john@example.com" , "George",
   "george@example.com");
- %name_email = (
   “John” => "john@example.com",
   “George” => "george@example.com",
  );
Common used of Hash:
- Print => print $name_email {"John"};
- Delete => delete $name_email {"John"};




                 August 2, 2012                           8
Control Structures - Conditional
• IF:   if (cond-expr 1) {…}
        elsif (cond-expr 2) {…}
        else {…}

        $num = 30;
        if ($num% 2 == 1) {
        print "an odd number.";
        } elsif ($num == 0) {
        print "zero.";
        } else {
        print "an even number.";
        }
        => an even number.


                 August 2, 2012     9
Loops
• For: for   ([init-expr]; [cond-expr]; [loop-expr]) {…}
      for ($i = 1; $i < 10; $i++) {
      print "$i ";
      }
  => 1 2 3 4 5 6 7 8 9
• While:     while (cond-expr) {…}
    $var1 = 1;
    $var2 = 8;
    while ($var1 < $var2) {          =>   1 2 3 4 5 6 7
      print "$var1 ";
      $var1 += 1;
    }


                  August 2, 2012                           10
Loops
• Until: until   (cond-expr) {…}


      $var1 = 1;$var2 = 8;
      until ($var2 < $var1) {
            print "$var2 ";
      $var2 -= 1;
      }
      => 8 7 6 5 4 3 2 1




                 August 2, 2012    11
Loops
• foreach:
  – foreach[$loopvar] (list) {…}

  $searchfor = "Schubert";
  @composers = ("Mozart", "Tchaikovsky", "Beethoven",
    "Dvorak", "Bach", "Handel", "Haydn", "Brahms",
    "Schubert", "Chopin");
  foreach $name (@composers) {
  if ($name eq $searchfor) {
    print "$searchfor is found!n";
    last;
  }
  }
  => Schubert is found!

              August 2, 2012                            12
Defining and using subroutines
$var1 = 100;
$var2 = 200;
$result = 0;

$result = my_sum();
print "$resultn";

sub my_sum {
   $tmp = $var1 + $var2;
   return $tmp;
}
=> 300




               August 2, 2012    13
Regular Expression
Perl Regular Expressions are a strong point of Perl:

•   b: word boundaries                               •   *: zero or more times
•   d: digits                                        •   +: one or more times
•   n: newline                                       •   ?: zero or one time
•   r: carriage return                               •   {p,q}: at least p times and at most q times
•   s: white space characters                        •   {p,}: at least p times
•   t: tab                                           •   {p}: exactly p times
•   w: alphanumeric characters
•   ^: beginning of string
•   $: end of string
•   Dot (.): any character
•   [bdkp]: characters b, d, k and p
•   [a-f]: characters a to f
•   [^a-f]: all characters except a to f
•   abc|def: string abc or string def
•   [:alpha:],[:punct:],[:digit:], … - use inside character class e.g., [[:alpha:]]


                            August 2, 2012                                                              14
Regular Expression : substitutions

• The “s/<partten>/<replace_partten>/” substitution
  operator does the ‘search and replace’
   - append a g to the operator to replace every occurrence.
   - append an i to the operator, to have the search case insensitive
   Examples:
      $line = “He is out with Barney. He is really
        happy!”;
      $line =~ s/Barney/Fred/; #He is out with Fred. He
        is really happy!
      $line =~ s/Barney/Wilma/;#He is out with Fred. He is
        really happy! (nothing happens as search failed)
      $line = “He is out with Fred. He is really happy”
      $line =~ s/He/She/g; #She is out with Fred. She is
        really happy!
      $text =~ s/bug/feature/g; # replace all occurrences
  of "bug"
                   August 2, 2012                                       15
Regular Expression : translations

• The "tr/<partten> /<replace_partten>/" operator
  performs a substitution on the individual characters.
 Examples:
      $x =~ tr/a/b/;            # Replace each "a" with "b".
      $x =~ tr/ /_/;     # Convert spaces to underlines.
      $x =~ tr/aeiou/AEIOU/; # Capitalise vowels.
             $x =~ tr/0-9/QERTYUIOPX/; # Digits to
  letters.
      $x =~ tr/A-Z/a-z/;         # Convert to lowercase.




               August 2, 2012                                  16
Regular Expression : matching

• The “m//” (or in short //) operator checks for matching .
 Examples:
      $x =~ m/dd/;            # Search 2 digits.
      $x =~ m/^This/;            # Search string begin with “This”.

      $x =~ m/string$/; # Search string end with “This” .
             $x =~ m /sds/; # Search a digit with white
  space in front and after it
      $x =~ m/^$/;        # Search for blank line.




               August 2, 2012                                     17
Regular Expression : split & join

• Split breaks up a string according to a separator.
      $line = “abc:def:g:h”;
      @fields = split(/:/,$line) =>
                        #(‘abc’,’def’,’g’,h’)
• Join glues together a bunch of pieces to make a string.
      @fields = (‘abc’,’def’,’g’,h’)
      $new_line = join(“:”,@fields) =>       #“abc:def:g:h”




               August 2, 2012                               18
Boolean : True / False ?



    Expression        1        '0.0'   a string    0      empty str   undef

if( $var )           true      true     true      false     false     false

if( defined $var )   true      true     true      true      true      false

if( $var eq '' )     false     false    false     false     true      true

if( $var == 0 )      false     true     true      true      true      true




                      August 2, 2012                                          19
Logical Tests: AND, OR

• AND
                                                Value of B
  Value of A      1             '0.0'    B string            0    empty str    undef

      1           1              0.0     B string            0    empty str    undef
    '0.0'         1              0.0     B string            0    empty str    undef
   A string       1              0.0     B string            0    empty str    undef
      0           0               0         0                0       0           0

  empty str    empty str     empty str   empty str    empty str   empty str   empty str

    undef       undef          undef      undef         undef      undef       undef




                      August 2, 2012                                                      20
Logical Tests: AND, OR

• OR
                                               Value of B
  Value of                                                       empty
                 1              '0.0'   B string            0               undef
     A                                                            str
      1          1                1        1                1      1           1
    '0.0'       0.0              0.0      0.0           0.0        0.0        0.0
   A string   A string       A string   A string     A string   A string    A string
      0          1               0.0    B string            0   empty str   undef
   empty
                 1               0.0    B string            0   empty str   undef
    str
   undef         1               0.0    B string            0   empty str   undef




                      August 2, 2012                                                   21
Exclusive OR: XOR

• XOR
                                       Value of B
  Value of                                                  empty
               1               '0.0'    a string     0              undef
     A                                                       str
      1       false           false      false      true    true    true
    '0.0'     false           false      false      true    true    true
   a string   false           false      false      true    true    true
      0       true             true      true       false   false   false
   empty
              true             true      true       false   false   false
    str
   undef      true             true      true       false   false   false




                     August 2, 2012                                         22
File handling

• Opening a File:
    open (SRC, “my_file.txt”);

• Reading from a File
    $line = <SRC>; # reads upto a newline character

• Closing a File
    close (SRC);




                   August 2, 2012                     23
File handling

• Opening a file for output:
      open (DST, “>my_file.txt”);
• Opening a file for appending
      open (DST, “>>my_file.txt”);
• Writing to a file:
      print DST “Printing my first line.n”;
• Safeguarding against opening a non existent file
    open (SRC, “file.txt”) || die “Could not open file.n”;




                  August 2, 2012                              24
File Test Operators

• Check to see if a file exists:

    if ( -e “file.txt”) {
         # The file exists!
    }

• Other file test operators:
    -r    readable
    -x    executable
    -d    is a directory
    -T   is a text file




                     August 2, 2012   25
File handling sample

• Program to copy a file to a destination file

   #!/usr/bin/perl -w
   open(SRC, “file.txt”) || die “Could not open source file.n”;
   open(DST, “>newfile.txt”);
   while ( $line = <SRC> )
       {
        print DST $line;
       }
   close SRC;
   close DST;



                  August 2, 2012                                   26
August 2, 2012   27

More Related Content

What's hot (20)

Introduction to Cascading Style Sheets (CSS)
Introduction to Cascading Style Sheets (CSS)Introduction to Cascading Style Sheets (CSS)
Introduction to Cascading Style Sheets (CSS)
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
html-css
html-csshtml-css
html-css
 
CSS for Beginners
CSS for BeginnersCSS for Beginners
CSS for Beginners
 
HTML CSS JS in Nut shell
HTML  CSS JS in Nut shellHTML  CSS JS in Nut shell
HTML CSS JS in Nut shell
 
CSS Day: CSS Grid Layout
CSS Day: CSS Grid Layout CSS Day: CSS Grid Layout
CSS Day: CSS Grid Layout
 
Cascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) helpCascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) help
 
Javascript
JavascriptJavascript
Javascript
 
Css Ppt
Css PptCss Ppt
Css Ppt
 
Cascading Style Sheets - Part 01
Cascading Style Sheets - Part 01Cascading Style Sheets - Part 01
Cascading Style Sheets - Part 01
 
CSS selectors
CSS selectorsCSS selectors
CSS selectors
 
CSS
CSSCSS
CSS
 
CSS Grid
CSS GridCSS Grid
CSS Grid
 
Css ppt
Css pptCss ppt
Css ppt
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Javascript Basic
Javascript BasicJavascript Basic
Javascript Basic
 
CSS Lists and Tables
CSS Lists and TablesCSS Lists and Tables
CSS Lists and Tables
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 

Viewers also liked

Viewers also liked (12)

Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Introduction to perl_ a scripting language
Introduction to perl_ a scripting languageIntroduction to perl_ a scripting language
Introduction to perl_ a scripting language
 
Introduction to Web Programming with Perl
Introduction to Web Programming with PerlIntroduction to Web Programming with Perl
Introduction to Web Programming with Perl
 
Server Side Programming
Server Side Programming Server Side Programming
Server Side Programming
 
Client & server side scripting
Client & server side scriptingClient & server side scripting
Client & server side scripting
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
 
Perl Programming - 02 Regular Expression
Perl Programming - 02 Regular ExpressionPerl Programming - 02 Regular Expression
Perl Programming - 02 Regular Expression
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
 
Introduction to Web Programming
Introduction to Web ProgrammingIntroduction to Web Programming
Introduction to Web Programming
 
Perl Programming - 01 Basic Perl
Perl Programming - 01 Basic PerlPerl Programming - 01 Basic Perl
Perl Programming - 01 Basic Perl
 

Similar to Basic perl programming

Similar to Basic perl programming (20)

7.1.intro perl
7.1.intro perl7.1.intro perl
7.1.intro perl
 
Scripting3
Scripting3Scripting3
Scripting3
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
tutorial7
tutorial7tutorial7
tutorial7
 
tutorial7
tutorial7tutorial7
tutorial7
 
Lecture 23
Lecture 23Lecture 23
Lecture 23
 
Crash Course in Perl – Perl tutorial for C programmers
Crash Course in Perl – Perl tutorial for C programmersCrash Course in Perl – Perl tutorial for C programmers
Crash Course in Perl – Perl tutorial for C programmers
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
 
Perl_Tutorial_v1
Perl_Tutorial_v1Perl_Tutorial_v1
Perl_Tutorial_v1
 
Perl_Tutorial_v1
Perl_Tutorial_v1Perl_Tutorial_v1
Perl_Tutorial_v1
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Dades i operadors
Dades i operadorsDades i operadors
Dades i operadors
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applications
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 

Recently uploaded

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 

Recently uploaded (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

Basic perl programming

  • 2. Agenda  Perl introduction  Variables  Control Structures  Loops  Defining and using subroutines  Regular Expression  Using Boolean (True/False)  File handling August 2, 2012 2
  • 3. Perl Introduction • Perl is a general-purpose programming language originally developed for text manipulation. Now, Perl used for web development, system administration, network programming, core generation and more. • Open Source and free licencing. • Support both procedural and OOP. • Excellent text handling and regular expressions August 2, 2012 3
  • 4. Installation Perl • Install ActivePerl 5.14.2 • Install Eclispse 3.6 or greater • In Eclipse IDE go to menu item “Help > Install New Software…” to install EPIC plugins of Perl at link: http://e-p-i-c.sf.net/updates/testing • After finish installed Perl plugins, go to menu “Run -> External Tools -> External Tools... “ to add and active the configuration for running Perl August 2, 2012 4
  • 5. Variables Scalar: $myString = “Hello” ;  hello $num1 = 10.5;  10.5 $num2 = $num1;  10.5 print “Number is :$num1”;  Number is :10.5 Prefix characters on Perl: • $: variable containing scalar values such as a number or a string • @: variable containing a list with numeric keys • %: variable containing a list with strings as keys • &: subroutine • *: matches all structures with the associated name August 2, 2012 5
  • 6. Variables Array (1): @colors = (“Red”, “Blue”, “Orange”); $colors[0] = “Red”; $colors[1] = “Blue”; $colors[2] = “Orange”; print “Our colors variable contains: @ colors ”;  Our colors variable contains : Red Blue Orange print “First element of the colors is: $colors[0]”;  First element of the colors is: Red @CombinedArray =(@Array1,@Array2);// merge 2 arrays @hundrednums = (101 .. 200); August 2, 2012 6
  • 7. Variables Array (2): Perl functions for working with arrays: • pop - remove last element of an array: • push - add an element to the end of array; • shift - removes first element of an array; • unshift - add an element to the beginning of array; • sort - sort an array. EG: @colors = (“Red”, “Blue”, “Orange”); print “Our colors variable contains: @ colors ”;  Our colors variable contains : Red Blue Orange pop @colors; print “Colors after applying pop function: @array1[0..$#array1]";  Colors after applying pop function: Red Blue August 2, 2012 7
  • 8. Variables Hashes: - %name_email = ("John", "john@example.com" , "George", "george@example.com"); - %name_email = ( “John” => "john@example.com", “George” => "george@example.com", ); Common used of Hash: - Print => print $name_email {"John"}; - Delete => delete $name_email {"John"}; August 2, 2012 8
  • 9. Control Structures - Conditional • IF: if (cond-expr 1) {…} elsif (cond-expr 2) {…} else {…} $num = 30; if ($num% 2 == 1) { print "an odd number."; } elsif ($num == 0) { print "zero."; } else { print "an even number."; } => an even number. August 2, 2012 9
  • 10. Loops • For: for ([init-expr]; [cond-expr]; [loop-expr]) {…} for ($i = 1; $i < 10; $i++) { print "$i "; } => 1 2 3 4 5 6 7 8 9 • While: while (cond-expr) {…} $var1 = 1; $var2 = 8; while ($var1 < $var2) { => 1 2 3 4 5 6 7 print "$var1 "; $var1 += 1; } August 2, 2012 10
  • 11. Loops • Until: until (cond-expr) {…} $var1 = 1;$var2 = 8; until ($var2 < $var1) { print "$var2 "; $var2 -= 1; } => 8 7 6 5 4 3 2 1 August 2, 2012 11
  • 12. Loops • foreach: – foreach[$loopvar] (list) {…} $searchfor = "Schubert"; @composers = ("Mozart", "Tchaikovsky", "Beethoven", "Dvorak", "Bach", "Handel", "Haydn", "Brahms", "Schubert", "Chopin"); foreach $name (@composers) { if ($name eq $searchfor) { print "$searchfor is found!n"; last; } } => Schubert is found! August 2, 2012 12
  • 13. Defining and using subroutines $var1 = 100; $var2 = 200; $result = 0; $result = my_sum(); print "$resultn"; sub my_sum { $tmp = $var1 + $var2; return $tmp; } => 300 August 2, 2012 13
  • 14. Regular Expression Perl Regular Expressions are a strong point of Perl: • b: word boundaries • *: zero or more times • d: digits • +: one or more times • n: newline • ?: zero or one time • r: carriage return • {p,q}: at least p times and at most q times • s: white space characters • {p,}: at least p times • t: tab • {p}: exactly p times • w: alphanumeric characters • ^: beginning of string • $: end of string • Dot (.): any character • [bdkp]: characters b, d, k and p • [a-f]: characters a to f • [^a-f]: all characters except a to f • abc|def: string abc or string def • [:alpha:],[:punct:],[:digit:], … - use inside character class e.g., [[:alpha:]] August 2, 2012 14
  • 15. Regular Expression : substitutions • The “s/<partten>/<replace_partten>/” substitution operator does the ‘search and replace’ - append a g to the operator to replace every occurrence. - append an i to the operator, to have the search case insensitive Examples: $line = “He is out with Barney. He is really happy!”; $line =~ s/Barney/Fred/; #He is out with Fred. He is really happy! $line =~ s/Barney/Wilma/;#He is out with Fred. He is really happy! (nothing happens as search failed) $line = “He is out with Fred. He is really happy” $line =~ s/He/She/g; #She is out with Fred. She is really happy! $text =~ s/bug/feature/g; # replace all occurrences of "bug" August 2, 2012 15
  • 16. Regular Expression : translations • The "tr/<partten> /<replace_partten>/" operator performs a substitution on the individual characters. Examples: $x =~ tr/a/b/; # Replace each "a" with "b". $x =~ tr/ /_/; # Convert spaces to underlines. $x =~ tr/aeiou/AEIOU/; # Capitalise vowels. $x =~ tr/0-9/QERTYUIOPX/; # Digits to letters. $x =~ tr/A-Z/a-z/; # Convert to lowercase. August 2, 2012 16
  • 17. Regular Expression : matching • The “m//” (or in short //) operator checks for matching . Examples: $x =~ m/dd/; # Search 2 digits. $x =~ m/^This/; # Search string begin with “This”. $x =~ m/string$/; # Search string end with “This” . $x =~ m /sds/; # Search a digit with white space in front and after it $x =~ m/^$/; # Search for blank line. August 2, 2012 17
  • 18. Regular Expression : split & join • Split breaks up a string according to a separator. $line = “abc:def:g:h”; @fields = split(/:/,$line) => #(‘abc’,’def’,’g’,h’) • Join glues together a bunch of pieces to make a string. @fields = (‘abc’,’def’,’g’,h’) $new_line = join(“:”,@fields) => #“abc:def:g:h” August 2, 2012 18
  • 19. Boolean : True / False ? Expression 1 '0.0' a string 0 empty str undef if( $var ) true true true false false false if( defined $var ) true true true true true false if( $var eq '' ) false false false false true true if( $var == 0 ) false true true true true true August 2, 2012 19
  • 20. Logical Tests: AND, OR • AND Value of B Value of A 1 '0.0' B string 0 empty str undef 1 1 0.0 B string 0 empty str undef '0.0' 1 0.0 B string 0 empty str undef A string 1 0.0 B string 0 empty str undef 0 0 0 0 0 0 0 empty str empty str empty str empty str empty str empty str empty str undef undef undef undef undef undef undef August 2, 2012 20
  • 21. Logical Tests: AND, OR • OR Value of B Value of empty 1 '0.0' B string 0 undef A str 1 1 1 1 1 1 1 '0.0' 0.0 0.0 0.0 0.0 0.0 0.0 A string A string A string A string A string A string A string 0 1 0.0 B string 0 empty str undef empty 1 0.0 B string 0 empty str undef str undef 1 0.0 B string 0 empty str undef August 2, 2012 21
  • 22. Exclusive OR: XOR • XOR Value of B Value of empty 1 '0.0' a string 0 undef A str 1 false false false true true true '0.0' false false false true true true a string false false false true true true 0 true true true false false false empty true true true false false false str undef true true true false false false August 2, 2012 22
  • 23. File handling • Opening a File: open (SRC, “my_file.txt”); • Reading from a File $line = <SRC>; # reads upto a newline character • Closing a File close (SRC); August 2, 2012 23
  • 24. File handling • Opening a file for output: open (DST, “>my_file.txt”); • Opening a file for appending open (DST, “>>my_file.txt”); • Writing to a file: print DST “Printing my first line.n”; • Safeguarding against opening a non existent file open (SRC, “file.txt”) || die “Could not open file.n”; August 2, 2012 24
  • 25. File Test Operators • Check to see if a file exists: if ( -e “file.txt”) { # The file exists! } • Other file test operators: -r readable -x executable -d is a directory -T is a text file August 2, 2012 25
  • 26. File handling sample • Program to copy a file to a destination file #!/usr/bin/perl -w open(SRC, “file.txt”) || die “Could not open source file.n”; open(DST, “>newfile.txt”); while ( $line = <SRC> ) { print DST $line; } close SRC; close DST; August 2, 2012 26

Editor's Notes

  1. Download Eclipse: http://www.eclipse.org/downloads/ Download ActivePerl 5.14.2: http://www.activestate.com/activeperl/downloads