SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

Cascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) helpCascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) helpcasestudyhelp
 
Cascading Style Sheets (CSS)
Cascading Style Sheets (CSS)Cascading Style Sheets (CSS)
Cascading Style Sheets (CSS)Harshil Darji
 
CSS INHERITANCE
CSS INHERITANCECSS INHERITANCE
CSS INHERITANCEAnuradha
 
Regular expression in javascript
Regular expression in javascriptRegular expression in javascript
Regular expression in javascriptToan Nguyen
 
Introduction to SASS
Introduction to SASSIntroduction to SASS
Introduction to SASSJon Dean
 
CSS For Backend Developers
CSS For Backend DevelopersCSS For Backend Developers
CSS For Backend Developers10Clouds
 
HTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventionsHTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventionsKnoldus Inc.
 
Transforming xml with XSLT
Transforming  xml with XSLTTransforming  xml with XSLT
Transforming xml with XSLTMalintha Adikari
 
9- Learn CSS Fundamentals / Pseudo-classes
9- Learn CSS Fundamentals / Pseudo-classes9- Learn CSS Fundamentals / Pseudo-classes
9- Learn CSS Fundamentals / Pseudo-classesIn a Rocket
 
How Cascading Style Sheets (CSS) Works
How Cascading Style Sheets (CSS) WorksHow Cascading Style Sheets (CSS) Works
How Cascading Style Sheets (CSS) WorksAmit Tyagi
 

Tendances (20)

SASS - CSS with Superpower
SASS - CSS with SuperpowerSASS - CSS with Superpower
SASS - CSS with Superpower
 
Css
CssCss
Css
 
Cascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) helpCascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) help
 
Cascading Style Sheets (CSS)
Cascading Style Sheets (CSS)Cascading Style Sheets (CSS)
Cascading Style Sheets (CSS)
 
Css borders
Css bordersCss borders
Css borders
 
Xml
XmlXml
Xml
 
CSS INHERITANCE
CSS INHERITANCECSS INHERITANCE
CSS INHERITANCE
 
Regular expression in javascript
Regular expression in javascriptRegular expression in javascript
Regular expression in javascript
 
Introduction to SASS
Introduction to SASSIntroduction to SASS
Introduction to SASS
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSS
 
CSS
CSSCSS
CSS
 
CSS For Backend Developers
CSS For Backend DevelopersCSS For Backend Developers
CSS For Backend Developers
 
Css Basics
Css BasicsCss Basics
Css Basics
 
Introduction to CSS3
Introduction to CSS3Introduction to CSS3
Introduction to CSS3
 
HTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventionsHTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventions
 
Css selectors
Css selectorsCss selectors
Css selectors
 
Css margins
Css marginsCss margins
Css margins
 
Transforming xml with XSLT
Transforming  xml with XSLTTransforming  xml with XSLT
Transforming xml with XSLT
 
9- Learn CSS Fundamentals / Pseudo-classes
9- Learn CSS Fundamentals / Pseudo-classes9- Learn CSS Fundamentals / Pseudo-classes
9- Learn CSS Fundamentals / Pseudo-classes
 
How Cascading Style Sheets (CSS) Works
How Cascading Style Sheets (CSS) WorksHow Cascading Style Sheets (CSS) Works
How Cascading Style Sheets (CSS) Works
 

En vedette (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
 

Similaire à Basic perl programming

Similaire à 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
 

Dernier

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
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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
 
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
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Dernier (20)

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
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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?
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

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

Notes de l'éditeur

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