SlideShare une entreprise Scribd logo
1  sur  17
Télécharger pour lire hors ligne
Programming in Perl

   Randy Julian
   Lilly Research Laboratories




The Crash Course…
   Getting Perl (CPAN, PPM)
   Getting/using the ptkdb debugger
   print “hello worldn”
   About variables: strings, numbers, arrays
   Operators and expressions
   About flow control
   Introduction to regular expressions
   Using Perl file I/O
   Basic subroutines and modules

An assembly of material harvested from various sources




                                                         1
Getting Perl
  Windows:
     www.activestate.com
       download “ActivePerl” (Either 5.6.x or 5.8.x)
     Run windows installer
  Linux:
     Probably already installed (standard on most)
     Latest version (5.6.x/5.8) via either RPM (from
     ActiveState or RedHat) or from source:
     cpan.perl.org




Getting the ptkdb debugger
  Windows:
     C:WINDOWS>perl -e “use Devel::ptkdb;”
       If this gives an error, you need to install the debugger
     PPM: Perl Package Manager
       C:WINDOWS>PPM
       PPM>install Devel::ptkdb
  Linux:
     $ perl -MCPAN -e ‘install “Devel::ptkdb” ’



                        From: “Perl for C Programmers”




                                                                  2
A Perl Tutoral
             Modified from: Nano Gough
http://www.computing.dcu.ie/~ngough/perl/tutorial.ppt




                                                        3
Perl Tutorial
Running Perl
Printing
Scalar Variables
Operations and Assignment
Arrays
Loops
Conditionals
File handling
Regular Expressions
Substitution
Split
Associative Arrays




                       Running Perl


#!/usr/local/bin/perl ( tells the file to run through perl)


Use .pl extension


perl programName (to run the program)


perl -d programName (to run using debugger)


perl – w programName (to run with warnings)




                                                              4
Printing


#The hash symbol (#) is use to comment lines of code
; Every statement in perl ends with a semi-colon (;)


print “Hello World. I love perl.”;
#prints: Hello World.I love perl.


print “Hello WorldnI love perln”;
#prints:
Hello World.
I love perl.




                             Scalar Variables
Strings/Numbers:
$name = “mary”;
$age = 27;
$income = 1_000_000; # underscores are ignored in numbers


                     Operations and Assignment
(* multiplication) ( division) (- subtraction)


$a = 1 + 2; # Add 1 and 2 and store in $a
$a = 5 % 2; # Remainder of 5 divided by 2
++$a; # Increment $a and then return it
$a++; # Return $a and then increment it
--$a; # Decrement $a and then return it
$a--; # Return $a and then decrement it




                                                            5
Operations and Assignment contd..


$a = 5; $b=7;
$a = $b; # Assign $b to $a ($a=7)
$a += $b; or $a=$a+b; # Add $b to $a ($a=12)
$a -= $b; or $a=$a-$b; # Subtract $b from $a ($a=-2)


Concatenation
$a = ‘Monday’; $b=‘Tuesday’;
$c=$a.” “.$b;
$c= ‘Monday Tuesday’; # Single quote: “don’t do anything to string”
$d= “$a and $b”; # Double quote: “interpret any variables in string”
print $d; # prints ‘Monday and Tuesday’;




                                Arrays
  Initialize an array/set to null
@colors=();
 Functions push and pop
#assign elements to array @colors
@colors=(“red”,”blue”,”yellow”);
#use push function to add an element to the end of array
push(@colors,”green”);
#colors now contains:
“red”,”blue”,”yellow”,”green”
#use pop function to remove an element from the end of array
pop(@colors);
#colors now contains
“red”, “blue”, “yellow”




                                                                       6
#Functions shift and unshift
@colors=(“red”,”blue”,”yellow”);
$new_el=“green”;
#use unshift to append $new_el to start of array
unshift(@colors, $new_el);
@colors is now:
“green”,“red”,”blue”,”yellow”


#use shift to remove an element from the front of array
shift(@colors);
@colors is now:
“red”,”blue”,”yellow”




  Accessing an element of the array


 @colors = (“red”,”blue”,”yellow”);
 print “$colors[0]” #prints: red


 $#colors #index of last element of array
 print “$colors[$#colors]; #prints: yellow


  print @colors #prints: redblueyellow
  print “@colors” #print: red blue yellow


  $colors = "@colors"; #assigns colors to string
  print $colors;          #prints: red blue yellow




                                                          7
Loops
#Loops can be used to iterate through elements of an array
 foreach Loop
        foreach $el (@colors)
        {
                print “The color is : $eln”;
        }


#The foreach loop iterates through the array element by #element. In
#the first iteration $el is assigned the value of the first element of
#colors (ie; red) etc..
#The result of executing this foreach statement is:
The color is : red
The color is : blue
The color is : yellow




                                 Testing
Numbers
$a == $b # Is $a numerically equal to $b?
# don’t use $a=$b as this will not compare but just assign $b to $a
 $a != $b # Is $a numerically unequal to $b?
$a<$b / $a>$b # Is $a less than/greater than $b
$a <=$b / $a >=$b # Is a less than or equal to/ g.t or eq to $b


Strings
$a eq $b # Is $a string-equal to $b?
 $a ne $b # Is $a string-unequal to $b?


#You can also use logical and, or and not:
($a && $b) # Is $a and $b true?
($a || $b) # Is either $a or $b true? !($a)




                                                                         8
Loops contd…
  For Loop
         for($i=0;$i<=$#colors;$i++)
         {
                 print “The color is : $colors[$i]n”;
         }


  While Loop
         $i=0;
         while($i=<=$#colors)
         {
                 print “$colors[$i]n”;
                 $i++;
         }




                              Conditionals
#if $a is equal red print the color is red
If($a eq ‘red’) { print “the color is $an”;}
#in any other case (if $a not equal to red) print $a is not red
else { print “The color $a is not redn”;}


#if $a is equal to 1 , add 2 to $a
If($a ==1){ $a = $a+2;}
#elsif $a is equal to 2, add 3 to $a
elsif ($a ==2) {$a =$a+3;}
#in any other case add 1 to $a
else { $a++;}


#if $a is equal to 1 AND $b is equal to red: print Color 1 is red
If(($a==1)||($b eq ‘red’)){print “Color $a is $bn”;}




                                                                    9
Some other string comparison operators:
         eq - equality
         ne - not equal
         lt - less than
         le - less than equal to
         gt - greater than
         ge - greater than equal to




                                  File handling
 Opening a file
$filename =“MyFile.txt”;
open(FILE,"/data/MyFile.txt") || die ("Cannot open file MyFile : $!n");


File: Filehandle for MyFile.txt
Die: If the file cannot be opened for reading the program will ‘die’ (ie quit
execution) and the reason for this will be returned in $!


The above file has been opened for reading : open(FILE,”filename”);
 To open a file for writing: open(FILE,”>OutFile.txt”);
Outfile.txt will be overwritten each time the program is executed
 To open a file for appending: open(FILE,”>>Append.txt”);
 Close File: close(FILE);




                                                                                10
File processing
#open input file for reading
open(IN,”InFile.txt”)|| die “Can’t open file….$!n”;
#open output file for writing
open(OUT,>”OutFile.txt”)|| die “Cant open file….$!n”;


while(<IN>)     #while there are still lines in InFile.txt
{
        $line=$_; #read in the lines one at a time
        chop($line); #remove end of line character
        #if $line meets conditional print to OutFile.txt
        if($line eq “Number 7”)
        {       print OUT “$linen”; } #endif
}#endWhile
close(IN); close(OUT); #close Files




                           Regular expressions


#A regular expression is contained in slashes, and matching occurs with
the =~ operator.
#The following expression is true if the string the appears in variable
$sentence.


$sentence =~ /the/
#The RE is case sensitive, so if $sentence = "The quick brown fox";
then the above match will be false.


$sentence !~/the/ (True) because the (lower case) is not in $sentence


#To eliminate case use i
$sentence =!/the/i; (True) because case has been eliminated with i




                                                                          11
These Special characters can be used to match the following:
.        # Any single character except a newline
^        # The beginning of the line or string
$        # The end of the line or string
*        # Zero or more of the last character
+        # One or more of the last character
?        # Zero or one of the last character


s+      (matches one or more spaces)
d+      (matches one or more digits)
t       (matches a tab)
n       (matches a new line)
b        (matches a word boundary)




                                                    test.txt:
      open(FILE,"test.txt");
                                                    #
      while(<FILE>)
      {                                             100 This matches.
              $line=$_;
              chop($line);                          200 This does not
              if($line !~ /this/i)                  That does not.
              {
                        print "$linen";
              }
      }

      close(FILE)



                                   #
                 Output:
                                   That does not.




                                                                        12
An Example using RE’s
TASK : We have a file containing lines in different formats. We want to
   pick out the lines which start with a digit and end in a period.


open(FILE,"test.txt");
while(<FILE>)
{
        $line=$_;
        chop($line);
        if($line =~ /^d+(.*).$/)
        {
                 print "$linen";
        }
}
close(FILE)
 ^d+ (specifies that $line must begin with a digit)
 (.*) This digit can be followed by any character any no. of times
 . This is followed by a period (The slash is included to make the ‘.’ literal )
 $. This specifies that the previous character (‘.’) must be the last on the line




                                                         test.txt:
     open(FILE,"test.txt");

     while(<FILE>)                                      #
     {
                                                        100 This matches.
            $line=$_;
            chop($line);                                200 This does not
            if($line =~ /^d+(.*).$/)
                                                        That does not.
            {
                     print "$linen";
            }
     }

     close(FILE)


                 Output:         100 This matches.




                                                                                    13
RE’s contd
  [a-z] (matches any lower case letter)
  [a-zA-z] (matches any letter)


In the previous example a line was matched under the following
condition:
if($line =~/^(d+)(.*).$/)


The RE would match the line: 10 people went to the concert.
(d+) = 10; This is assigned to default variable $1
 (.*) = “people went to the concert”; This is assigned to $2
Perl groups the elements specified by () together and assigns it a
default variable: $1,$2…etc.
print “$1n”; # prints : people went to the concert




                               Substitution


#substitution is a useful facility in perl which can be used to
replace one element with another


#replaces all instances of lafayette (lc) in $sentence to Lafayette (uc);
$sentence =~ s/lafayette/Lafayette/;


#replaces all instances of red in $sentence to blue
$sentence =~s/red/blue/;


Example
$sentence= “the red and white dress”;
$sentence =~s/red/blue/;
$sentence is now = “the blue and white dress”




                                                                            14
Split


  #split is a useful function : splits up a string and puts it on an
  #array
  $example = “Luke I am your father”;
  @name=split(/s+/,$example);
  @name = “Luke”, “I”, “am”, “your”, “father”


  #using split you can also assign elements to variables
  $name = “Luke:Skywalker”;
  ($first_name, $surname)=split(/:/,$name);
  $first_name = “Luke”;
  $surname=“Skywalker”;




                  Associative arrays / hashes
  The elements of associative arrays have keys with associated values
Initialize
%Mygrades=();
Assign elements
$Mygrades{‘CHM696’}=90;
$Mygrades{‘CHM621’}=70;
$Mygrades{‘CHM624’}=50;
Printing
while(($key,$value)=each(%Mygrades))
{print “$key => $valuen”;}
                                   ptkdb has trouble with each()
Prints:
CHM696 => 90
CHM621 => 70
CHM624 => 50




                                                                        15
Plain Old Documentation (POD)
# The lines from here to the =cut are part of    Sample run:
# Perl’s internal documentation system. If you
# want view the documentation use the                   perl test_ave.pl
# command:                                              Read 64 items
                                                        Moving average
#     pod2text <script>
                                                        4.59666666666667
#                                                       4.60666666666667
=pod                                                    4.64
                                                        4.67666666666667
=head1 NAME                                             4.71
                                                        ...
test_ave.pl - Test the moving average program
                                                 =head1 AUTHOR
=head1 SYNOPSIS
                                                 Steve Oualline,
                                                      E<lt>oualline@www.oualline.comE<gt>.
  perl test_ave.pl
                                                 =head1 COPYRIGHT
=head1 DESCRIPTION
                                                 Copyright 2002 Steve Oualline.
The I<test_ave.pl> reads a series of numbers     This program is distributed under the GPL.
     from I<num.txt>
and print a moving average spanning three data   =cut
     points.

=head1 EXAMPLES




 Sub-routines
my @raw_data = ();
my $flag = read_data("num.txt");
if (not $flag) {
   die("Could not read file");
}
                         sub read_data($)
                         {
                            my $file = shift;  # The file to read
                            open DATA_FILE, "<$file" or return (undef);
                            @raw_data = <DATA_FILE>;
                            chomp(@raw_data);
                            close(DATA_FILE);
                            return (1); # Success
                         }




                                                                                              16
sub moving_average($)
{
  my $increment = shift; # Increment for average
  my $index;                     # Current item for average
  my @result;                    # Averaged data

  for ($index = 0;
     $index <= $#raw_data - $increment;
     $index++) {
     my $total = sum(@raw_data[$index..$index + $increment -1]);
     push (@result, $total / $increment);
  }
  return(@result);
}                              sub sum(@)
                               {
                                  my @array = @_;  # The array to sum
                                  my $the_sum = 0; # Result so far
here a selection of
the @raw_data                    foreach my $element (@array) {
                                    $the_sum += $element;
array is passed to               }
sum() using the                  return ($the_sum);
                             }
.. operator




                                                                        17

Contenu connexe

Tendances

Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
Lin Yo-An
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
Elie Obeid
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
Dave Cross
 

Tendances (17)

Introduction to Perl and BioPerl
Introduction to Perl and BioPerlIntroduction to Perl and BioPerl
Introduction to Perl and BioPerl
 
Subroutines
SubroutinesSubroutines
Subroutines
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev Assistant
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
 
Introduction to Perl Best Practices
Introduction to Perl Best PracticesIntroduction to Perl Best Practices
Introduction to Perl Best Practices
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
 
Basic perl programming
Basic perl programmingBasic perl programming
Basic perl programming
 
Cli the other SAPI confoo11
Cli the other SAPI confoo11Cli the other SAPI confoo11
Cli the other SAPI confoo11
 
Perl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally InsanePerl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally Insane
 
PHP Conference Asia 2016
PHP Conference Asia 2016PHP Conference Asia 2016
PHP Conference Asia 2016
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
 
Syntax
SyntaxSyntax
Syntax
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
 

En vedette (8)

Getting started with Pod::Weaver
Getting started with Pod::WeaverGetting started with Pod::Weaver
Getting started with Pod::Weaver
 
Have more fun with Perl via Questhub
Have more fun with Perl via QuesthubHave more fun with Perl via Questhub
Have more fun with Perl via Questhub
 
CPAN Exporter modules for Perl 5
CPAN Exporter modules for Perl 5CPAN Exporter modules for Perl 5
CPAN Exporter modules for Perl 5
 
CPAN Curation
CPAN CurationCPAN Curation
CPAN Curation
 
Dist::Zilla - A very brief introduction
Dist::Zilla - A very brief introductionDist::Zilla - A very brief introduction
Dist::Zilla - A very brief introduction
 
Hank Torbert Avondale Ventures
Hank Torbert Avondale VenturesHank Torbert Avondale Ventures
Hank Torbert Avondale Ventures
 
Co-teaching can be wonderful !
Co-teaching can be wonderful !Co-teaching can be wonderful !
Co-teaching can be wonderful !
 
Hank torbert
Hank torbertHank torbert
Hank torbert
 

Similaire à Lecture19-20

Perl courseparti
Perl coursepartiPerl courseparti
Perl courseparti
ernlow
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationLecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administration
Mohammed Farrag
 
Scripting3
Scripting3Scripting3
Scripting3
Nao Dara
 

Similaire à Lecture19-20 (20)

Tutorial perl programming basic eng ver
Tutorial perl programming basic eng verTutorial perl programming basic eng ver
Tutorial perl programming basic eng ver
 
Perl courseparti
Perl coursepartiPerl courseparti
Perl courseparti
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
tutorial7
tutorial7tutorial7
tutorial7
 
tutorial7
tutorial7tutorial7
tutorial7
 
Programming in perl style
Programming in perl styleProgramming in perl style
Programming in perl style
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsYou Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager Needs
 
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationLecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administration
 
Scripting3
Scripting3Scripting3
Scripting3
 
Data Types Master
Data Types MasterData Types Master
Data Types Master
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 

Plus de tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
tutorialsruby
 

Plus de tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
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?
 
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...
 
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...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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
 
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
 
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
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
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
 
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
 

Lecture19-20

  • 1. Programming in Perl Randy Julian Lilly Research Laboratories The Crash Course… Getting Perl (CPAN, PPM) Getting/using the ptkdb debugger print “hello worldn” About variables: strings, numbers, arrays Operators and expressions About flow control Introduction to regular expressions Using Perl file I/O Basic subroutines and modules An assembly of material harvested from various sources 1
  • 2. Getting Perl Windows: www.activestate.com download “ActivePerl” (Either 5.6.x or 5.8.x) Run windows installer Linux: Probably already installed (standard on most) Latest version (5.6.x/5.8) via either RPM (from ActiveState or RedHat) or from source: cpan.perl.org Getting the ptkdb debugger Windows: C:WINDOWS>perl -e “use Devel::ptkdb;” If this gives an error, you need to install the debugger PPM: Perl Package Manager C:WINDOWS>PPM PPM>install Devel::ptkdb Linux: $ perl -MCPAN -e ‘install “Devel::ptkdb” ’ From: “Perl for C Programmers” 2
  • 3. A Perl Tutoral Modified from: Nano Gough http://www.computing.dcu.ie/~ngough/perl/tutorial.ppt 3
  • 4. Perl Tutorial Running Perl Printing Scalar Variables Operations and Assignment Arrays Loops Conditionals File handling Regular Expressions Substitution Split Associative Arrays Running Perl #!/usr/local/bin/perl ( tells the file to run through perl) Use .pl extension perl programName (to run the program) perl -d programName (to run using debugger) perl – w programName (to run with warnings) 4
  • 5. Printing #The hash symbol (#) is use to comment lines of code ; Every statement in perl ends with a semi-colon (;) print “Hello World. I love perl.”; #prints: Hello World.I love perl. print “Hello WorldnI love perln”; #prints: Hello World. I love perl. Scalar Variables Strings/Numbers: $name = “mary”; $age = 27; $income = 1_000_000; # underscores are ignored in numbers Operations and Assignment (* multiplication) ( division) (- subtraction) $a = 1 + 2; # Add 1 and 2 and store in $a $a = 5 % 2; # Remainder of 5 divided by 2 ++$a; # Increment $a and then return it $a++; # Return $a and then increment it --$a; # Decrement $a and then return it $a--; # Return $a and then decrement it 5
  • 6. Operations and Assignment contd.. $a = 5; $b=7; $a = $b; # Assign $b to $a ($a=7) $a += $b; or $a=$a+b; # Add $b to $a ($a=12) $a -= $b; or $a=$a-$b; # Subtract $b from $a ($a=-2) Concatenation $a = ‘Monday’; $b=‘Tuesday’; $c=$a.” “.$b; $c= ‘Monday Tuesday’; # Single quote: “don’t do anything to string” $d= “$a and $b”; # Double quote: “interpret any variables in string” print $d; # prints ‘Monday and Tuesday’; Arrays Initialize an array/set to null @colors=(); Functions push and pop #assign elements to array @colors @colors=(“red”,”blue”,”yellow”); #use push function to add an element to the end of array push(@colors,”green”); #colors now contains: “red”,”blue”,”yellow”,”green” #use pop function to remove an element from the end of array pop(@colors); #colors now contains “red”, “blue”, “yellow” 6
  • 7. #Functions shift and unshift @colors=(“red”,”blue”,”yellow”); $new_el=“green”; #use unshift to append $new_el to start of array unshift(@colors, $new_el); @colors is now: “green”,“red”,”blue”,”yellow” #use shift to remove an element from the front of array shift(@colors); @colors is now: “red”,”blue”,”yellow” Accessing an element of the array @colors = (“red”,”blue”,”yellow”); print “$colors[0]” #prints: red $#colors #index of last element of array print “$colors[$#colors]; #prints: yellow print @colors #prints: redblueyellow print “@colors” #print: red blue yellow $colors = "@colors"; #assigns colors to string print $colors; #prints: red blue yellow 7
  • 8. Loops #Loops can be used to iterate through elements of an array foreach Loop foreach $el (@colors) { print “The color is : $eln”; } #The foreach loop iterates through the array element by #element. In #the first iteration $el is assigned the value of the first element of #colors (ie; red) etc.. #The result of executing this foreach statement is: The color is : red The color is : blue The color is : yellow Testing Numbers $a == $b # Is $a numerically equal to $b? # don’t use $a=$b as this will not compare but just assign $b to $a $a != $b # Is $a numerically unequal to $b? $a<$b / $a>$b # Is $a less than/greater than $b $a <=$b / $a >=$b # Is a less than or equal to/ g.t or eq to $b Strings $a eq $b # Is $a string-equal to $b? $a ne $b # Is $a string-unequal to $b? #You can also use logical and, or and not: ($a && $b) # Is $a and $b true? ($a || $b) # Is either $a or $b true? !($a) 8
  • 9. Loops contd… For Loop for($i=0;$i<=$#colors;$i++) { print “The color is : $colors[$i]n”; } While Loop $i=0; while($i=<=$#colors) { print “$colors[$i]n”; $i++; } Conditionals #if $a is equal red print the color is red If($a eq ‘red’) { print “the color is $an”;} #in any other case (if $a not equal to red) print $a is not red else { print “The color $a is not redn”;} #if $a is equal to 1 , add 2 to $a If($a ==1){ $a = $a+2;} #elsif $a is equal to 2, add 3 to $a elsif ($a ==2) {$a =$a+3;} #in any other case add 1 to $a else { $a++;} #if $a is equal to 1 AND $b is equal to red: print Color 1 is red If(($a==1)||($b eq ‘red’)){print “Color $a is $bn”;} 9
  • 10. Some other string comparison operators: eq - equality ne - not equal lt - less than le - less than equal to gt - greater than ge - greater than equal to File handling Opening a file $filename =“MyFile.txt”; open(FILE,"/data/MyFile.txt") || die ("Cannot open file MyFile : $!n"); File: Filehandle for MyFile.txt Die: If the file cannot be opened for reading the program will ‘die’ (ie quit execution) and the reason for this will be returned in $! The above file has been opened for reading : open(FILE,”filename”); To open a file for writing: open(FILE,”>OutFile.txt”); Outfile.txt will be overwritten each time the program is executed To open a file for appending: open(FILE,”>>Append.txt”); Close File: close(FILE); 10
  • 11. File processing #open input file for reading open(IN,”InFile.txt”)|| die “Can’t open file….$!n”; #open output file for writing open(OUT,>”OutFile.txt”)|| die “Cant open file….$!n”; while(<IN>) #while there are still lines in InFile.txt { $line=$_; #read in the lines one at a time chop($line); #remove end of line character #if $line meets conditional print to OutFile.txt if($line eq “Number 7”) { print OUT “$linen”; } #endif }#endWhile close(IN); close(OUT); #close Files Regular expressions #A regular expression is contained in slashes, and matching occurs with the =~ operator. #The following expression is true if the string the appears in variable $sentence. $sentence =~ /the/ #The RE is case sensitive, so if $sentence = "The quick brown fox"; then the above match will be false. $sentence !~/the/ (True) because the (lower case) is not in $sentence #To eliminate case use i $sentence =!/the/i; (True) because case has been eliminated with i 11
  • 12. These Special characters can be used to match the following: . # Any single character except a newline ^ # The beginning of the line or string $ # The end of the line or string * # Zero or more of the last character + # One or more of the last character ? # Zero or one of the last character s+ (matches one or more spaces) d+ (matches one or more digits) t (matches a tab) n (matches a new line) b (matches a word boundary) test.txt: open(FILE,"test.txt"); # while(<FILE>) { 100 This matches. $line=$_; chop($line); 200 This does not if($line !~ /this/i) That does not. { print "$linen"; } } close(FILE) # Output: That does not. 12
  • 13. An Example using RE’s TASK : We have a file containing lines in different formats. We want to pick out the lines which start with a digit and end in a period. open(FILE,"test.txt"); while(<FILE>) { $line=$_; chop($line); if($line =~ /^d+(.*).$/) { print "$linen"; } } close(FILE) ^d+ (specifies that $line must begin with a digit) (.*) This digit can be followed by any character any no. of times . This is followed by a period (The slash is included to make the ‘.’ literal ) $. This specifies that the previous character (‘.’) must be the last on the line test.txt: open(FILE,"test.txt"); while(<FILE>) # { 100 This matches. $line=$_; chop($line); 200 This does not if($line =~ /^d+(.*).$/) That does not. { print "$linen"; } } close(FILE) Output: 100 This matches. 13
  • 14. RE’s contd [a-z] (matches any lower case letter) [a-zA-z] (matches any letter) In the previous example a line was matched under the following condition: if($line =~/^(d+)(.*).$/) The RE would match the line: 10 people went to the concert. (d+) = 10; This is assigned to default variable $1 (.*) = “people went to the concert”; This is assigned to $2 Perl groups the elements specified by () together and assigns it a default variable: $1,$2…etc. print “$1n”; # prints : people went to the concert Substitution #substitution is a useful facility in perl which can be used to replace one element with another #replaces all instances of lafayette (lc) in $sentence to Lafayette (uc); $sentence =~ s/lafayette/Lafayette/; #replaces all instances of red in $sentence to blue $sentence =~s/red/blue/; Example $sentence= “the red and white dress”; $sentence =~s/red/blue/; $sentence is now = “the blue and white dress” 14
  • 15. Split #split is a useful function : splits up a string and puts it on an #array $example = “Luke I am your father”; @name=split(/s+/,$example); @name = “Luke”, “I”, “am”, “your”, “father” #using split you can also assign elements to variables $name = “Luke:Skywalker”; ($first_name, $surname)=split(/:/,$name); $first_name = “Luke”; $surname=“Skywalker”; Associative arrays / hashes The elements of associative arrays have keys with associated values Initialize %Mygrades=(); Assign elements $Mygrades{‘CHM696’}=90; $Mygrades{‘CHM621’}=70; $Mygrades{‘CHM624’}=50; Printing while(($key,$value)=each(%Mygrades)) {print “$key => $valuen”;} ptkdb has trouble with each() Prints: CHM696 => 90 CHM621 => 70 CHM624 => 50 15
  • 16. Plain Old Documentation (POD) # The lines from here to the =cut are part of Sample run: # Perl’s internal documentation system. If you # want view the documentation use the perl test_ave.pl # command: Read 64 items Moving average # pod2text <script> 4.59666666666667 # 4.60666666666667 =pod 4.64 4.67666666666667 =head1 NAME 4.71 ... test_ave.pl - Test the moving average program =head1 AUTHOR =head1 SYNOPSIS Steve Oualline, E<lt>oualline@www.oualline.comE<gt>. perl test_ave.pl =head1 COPYRIGHT =head1 DESCRIPTION Copyright 2002 Steve Oualline. The I<test_ave.pl> reads a series of numbers This program is distributed under the GPL. from I<num.txt> and print a moving average spanning three data =cut points. =head1 EXAMPLES Sub-routines my @raw_data = (); my $flag = read_data("num.txt"); if (not $flag) { die("Could not read file"); } sub read_data($) { my $file = shift; # The file to read open DATA_FILE, "<$file" or return (undef); @raw_data = <DATA_FILE>; chomp(@raw_data); close(DATA_FILE); return (1); # Success } 16
  • 17. sub moving_average($) { my $increment = shift; # Increment for average my $index; # Current item for average my @result; # Averaged data for ($index = 0; $index <= $#raw_data - $increment; $index++) { my $total = sum(@raw_data[$index..$index + $increment -1]); push (@result, $total / $increment); } return(@result); } sub sum(@) { my @array = @_; # The array to sum my $the_sum = 0; # Result so far here a selection of the @raw_data foreach my $element (@array) { $the_sum += $element; array is passed to } sum() using the return ($the_sum); } .. operator 17