SlideShare a Scribd company logo
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

More Related Content

What's hot (17)

PDF
Introduction to Perl and BioPerl
Bioinformatics and Computational Biosciences Branch
 
PDF
Perl.Hacks.On.Vim
Lin Yo-An
 
ODP
Perl Introduction
Marcos Rebelo
 
PDF
Improving Dev Assistant
Dave Cross
 
PDF
Perl programming language
Elie Obeid
 
ODP
Introduction to Perl - Day 2
Dave Cross
 
KEY
Introduction to Perl Best Practices
José Castro
 
PDF
Perl Scripting
Varadharajan Mukundan
 
PPT
Basic perl programming
Thang Nguyen
 
PDF
Perl 5.10 for People Who Aren't Totally Insane
Ricardo Signes
 
PDF
Cli the other SAPI confoo11
Combell NV
 
PDF
PHP Conference Asia 2016
Britta Alex
 
PPTX
PHP Powerpoint -- Teach PHP with this
Ian Macali
 
PDF
DBIx::Class beginners
leo lapworth
 
PDF
perl_lessons
tutorialsruby
 
Introduction to Perl and BioPerl
Bioinformatics and Computational Biosciences Branch
 
Perl.Hacks.On.Vim
Lin Yo-An
 
Perl Introduction
Marcos Rebelo
 
Improving Dev Assistant
Dave Cross
 
Perl programming language
Elie Obeid
 
Introduction to Perl - Day 2
Dave Cross
 
Introduction to Perl Best Practices
José Castro
 
Perl Scripting
Varadharajan Mukundan
 
Basic perl programming
Thang Nguyen
 
Perl 5.10 for People Who Aren't Totally Insane
Ricardo Signes
 
Cli the other SAPI confoo11
Combell NV
 
PHP Conference Asia 2016
Britta Alex
 
PHP Powerpoint -- Teach PHP with this
Ian Macali
 
DBIx::Class beginners
leo lapworth
 
perl_lessons
tutorialsruby
 

Viewers also liked (7)

PDF
dr_1
tutorialsruby
 
PDF
geoext_dwins
tutorialsruby
 
PDF
Day4
tutorialsruby
 
PDF
collapsible-panels-tutorial
tutorialsruby
 
PDF
treeview
tutorialsruby
 
PDF
handout
tutorialsruby
 
PDF
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
tutorialsruby
 
geoext_dwins
tutorialsruby
 
collapsible-panels-tutorial
tutorialsruby
 
treeview
tutorialsruby
 
handout
tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
tutorialsruby
 
Ad

Similar to Lecture19-20 (20)

PDF
Practical approach to perl day1
Rakesh Mukundan
 
PDF
tutorial7
tutorialsruby
 
PDF
tutorial7
tutorialsruby
 
PDF
Scripting3
Nao Dara
 
PDF
Perl_Tutorial_v1
tutorialsruby
 
PDF
Perl_Tutorial_v1
tutorialsruby
 
PPT
7.1.intro perl
Varun Chhangani
 
PPT
Introduction to Perl
NBACriteria2SICET
 
PDF
newperl5
tutorialsruby
 
PDF
newperl5
tutorialsruby
 
PPT
Perl Intro 3 Datalog Parsing
Shaun Griffith
 
PDF
Tutorial perl programming basic eng ver
Qrembiezs Intruder
 
PDF
Perl intro
Kanchilug
 
PPT
Perl Intro 4 Debugger
Shaun Griffith
 
PDF
perl_lessons
tutorialsruby
 
PPT
Perl Intro 2 First Program
Shaun Griffith
 
PPT
Perl tutorial
Manav Prasad
 
PDF
Lecture4
tutorialsruby
 
PDF
Lecture4
tutorialsruby
 
PDF
Unit VI
Bhavsingh Maloth
 
Practical approach to perl day1
Rakesh Mukundan
 
tutorial7
tutorialsruby
 
tutorial7
tutorialsruby
 
Scripting3
Nao Dara
 
Perl_Tutorial_v1
tutorialsruby
 
Perl_Tutorial_v1
tutorialsruby
 
7.1.intro perl
Varun Chhangani
 
Introduction to Perl
NBACriteria2SICET
 
newperl5
tutorialsruby
 
newperl5
tutorialsruby
 
Perl Intro 3 Datalog Parsing
Shaun Griffith
 
Tutorial perl programming basic eng ver
Qrembiezs Intruder
 
Perl intro
Kanchilug
 
Perl Intro 4 Debugger
Shaun Griffith
 
perl_lessons
tutorialsruby
 
Perl Intro 2 First Program
Shaun Griffith
 
Perl tutorial
Manav Prasad
 
Lecture4
tutorialsruby
 
Lecture4
tutorialsruby
 
Ad

More from tutorialsruby (20)

PDF
&lt;img src="../i/r_14.png" />
tutorialsruby
 
PDF
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
tutorialsruby
 
PDF
&lt;img src="../i/r_14.png" />
tutorialsruby
 
PDF
&lt;img src="../i/r_14.png" />
tutorialsruby
 
PDF
Standardization and Knowledge Transfer – INS0
tutorialsruby
 
PDF
xhtml_basics
tutorialsruby
 
PDF
xhtml_basics
tutorialsruby
 
PDF
xhtml-documentation
tutorialsruby
 
PDF
xhtml-documentation
tutorialsruby
 
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
PDF
HowTo_CSS
tutorialsruby
 
PDF
HowTo_CSS
tutorialsruby
 
PDF
BloggingWithStyle_2008
tutorialsruby
 
PDF
BloggingWithStyle_2008
tutorialsruby
 
PDF
cascadingstylesheets
tutorialsruby
 
PDF
cascadingstylesheets
tutorialsruby
 
PDF
Winter%200405%20-%20Advanced%20Javascript
tutorialsruby
 
&lt;img src="../i/r_14.png" />
tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
tutorialsruby
 
&lt;img src="../i/r_14.png" />
tutorialsruby
 
&lt;img src="../i/r_14.png" />
tutorialsruby
 
Standardization and Knowledge Transfer – INS0
tutorialsruby
 
xhtml_basics
tutorialsruby
 
xhtml_basics
tutorialsruby
 
xhtml-documentation
tutorialsruby
 
xhtml-documentation
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
HowTo_CSS
tutorialsruby
 
HowTo_CSS
tutorialsruby
 
BloggingWithStyle_2008
tutorialsruby
 
BloggingWithStyle_2008
tutorialsruby
 
cascadingstylesheets
tutorialsruby
 
cascadingstylesheets
tutorialsruby
 
Winter%200405%20-%20Advanced%20Javascript
tutorialsruby
 

Recently uploaded (20)

PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 

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>[email protected]<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