SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Getting Started with HTML5 in Tech Com (STC 2012)
Getting Started with HTML5 in Tech Com (STC 2012)Getting Started with HTML5 in Tech Com (STC 2012)
Getting Started with HTML5 in Tech Com (STC 2012)
 
CSS Day: CSS Grid Layout
CSS Day: CSS Grid Layout CSS Day: CSS Grid Layout
CSS Day: CSS Grid Layout
 
Css
CssCss
Css
 
CSS Font & Text style
CSS Font & Text style CSS Font & Text style
CSS Font & Text style
 
Less vs sass
Less vs sassLess vs sass
Less vs sass
 
SASS - Syntactically Awesome Stylesheet
SASS - Syntactically Awesome StylesheetSASS - Syntactically Awesome Stylesheet
SASS - Syntactically Awesome Stylesheet
 
Html, CSS & Web Designing
Html, CSS & Web DesigningHtml, CSS & Web Designing
Html, CSS & Web Designing
 
Navigation and Link
Navigation and LinkNavigation and Link
Navigation and Link
 
Bootstrap 3
Bootstrap 3Bootstrap 3
Bootstrap 3
 
World of CSS Grid
World of CSS GridWorld of CSS Grid
World of CSS Grid
 
SASS - CSS with Superpower
SASS - CSS with SuperpowerSASS - CSS with Superpower
SASS - CSS with Superpower
 
Introduction to sass
Introduction to sassIntroduction to sass
Introduction to sass
 
Flexbox
FlexboxFlexbox
Flexbox
 
Server Side Programming
Server Side ProgrammingServer Side Programming
Server Side Programming
 
Html vs xhtml
Html vs xhtmlHtml vs xhtml
Html vs xhtml
 
Javascript
JavascriptJavascript
Javascript
 
Java script array
Java script arrayJava script array
Java script array
 
Css borders
Css bordersCss borders
Css borders
 
CSS Selectors
CSS SelectorsCSS Selectors
CSS Selectors
 
Html
HtmlHtml
Html
 

Andere mochten auch

Andere mochten auch (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
 

Ähnlich wie Basic Perl programming essentials

Ähnlich wie Basic Perl programming essentials (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
 

Kürzlich hochgeladen

Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Kürzlich hochgeladen (20)

Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Basic Perl programming essentials

  • 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

Hinweis der Redaktion

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