Perl Programming WeeSan Lee

Slides:



Advertisements
Similar presentations
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
Advertisements

An Introduction to Perl with Applications in Web Page Scraping.
Second edition Your UNIX: The Ultimate Guide Das © 2006 The McGraw-Hill Companies, Inc. All rights reserved. UNIX – The Master Manipulator perl Perl is.
Programming Perls* Objective: To introduce students to the perl language. –Perl is a language for getting your job done. –Making Easy Things Easy & Hard.
CSET4100 – Fall 2009 Perl Introduction Scalar Data, Operators & Control Blocks Acknowledgements: Slides adapted from NYU Computer Science course on UNIX.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
CS311 – Today's class Perl – Practical Extraction Report Language. Assignment 2 discussion Lecture 071CS Operating Systems I.
1 Perl Tutorial Adapted from slides found at: original author is not indicated Bioinformatics Orientation 2008 Eric Bishop.
Scripting Languages Chapter 6 I/O Basics. Input from STDIN We’ve been doing so with $line = chomp($line); Same as chomp($line= ); line input op gives.
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
Practical Extraction & Report Language Picture taken from
Perl Basics A Perl Tutorial NLP Course What is Perl?  Practical Extraction and Report Language  Interpreted Language Optimized for String Manipulation.
Introduction to Perl. How to run perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Your program/script.
CSC3530 Software Technology Tutorial Two PERL Basics.
Lecture 2 BNFO 135 Usman Roshan. Perl variables Scalar –Number –String Examples –$myname = “Roshan”; –$year = 2006;
Perl File I/O and Arrays. File I/O Perl allows to open a file to read, write, or append As well as pipe input or output to another program. —We get to.
Introduction to perl Research Computing/Larry Mason February 17, 2009.
3ex.1 Note: use strict on the first line Because of a bug in the Perl Express debugger you have to put “use strict;” on the first line of your scripts.
Computer Programming for Biologists Class 2 Oct 31 st, 2014 Karsten Hokamp
Basic Perl Programming
Practical Extraction & Report Language PERL Joseph Beltran.
Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.
Introduction to Perl & BioPerl Dr G. P. S. Raghava Bioinformatics Centre Bioinformatics Centre IMTECH, Chandigarh Web:
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
Linux Operating System
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CS 330 Programming Languages 10 / 07 / 2008 Instructor: Michael Eckmann.
Books. Perl Perl (Practical Extraction and Report Language) by Larry Wall Perl 1.0 was released to usenet's alt.comp.sources in 1987 Perl 5 was released.
Perl Language Yize Chen CS354. History Perl was designed by Larry Wall in 1987 as a text processing language Perl has revised several times and becomes.
Perl: Lecture 1 The language. What Perl is Merger of Unix tools – Very popular under UNIX – shell, sed, awk Programming language – C syntax Scripting.
Chapter 9: Perl Programming Practical Extraction and Report Language Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
Chapter 9: Perl (continue) Advanced Perl Programming Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Introduction to Unix – CS 21
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
Computer Programming for Biologists Class 3 Nov 13 th, 2014 Karsten Hokamp
Introduction to Perl “Practical Extraction and Report Language” “Pathologically Eclectic Rubbish Lister”
CS 330 Programming Languages 10 / 02 / 2007 Instructor: Michael Eckmann.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Perl Basics. sh-bang !!!! Every perl program starts with a sh-bang line #!/usr/bin/perl # hello.pl printf “Hello, world!\n”; printf STDOUT “Hello, world!\n”;
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83,
LING/C SC/PSYC 438/538 Lecture 8 Sandiway Fong. Adminstrivia Homework 4 not yet graded …
– Introduction to Perl 12/13/ Introduction to Perl - Strings, Truth and Regex Introduction to Perl Session 2 · manipulating.
Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004.
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.
Topic 2: Working with scalars CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 2, pages 19-38, Programming Perl 3rd edition chapter.
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
 2001 Prentice Hall, Inc. All rights reserved. Chapter 7 - Introduction to Common Gateway Interface (CGI) Outline 7.1Introduction 7.2A Simple HTTP Transaction.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
Computer Programming for Biologists Class 4 Nov 14 th, 2014 Karsten Hokamp
PERL By C. Shing ITEC Dept Radford University. Objectives Understand the history Understand constants and variables Understand operators Understand control.
CSC 4630 Meeting 17 March 21, Exam/Quiz Schedule Due to ice, travel, research and other commitments that we all have: –Quiz 2, scheduled for Monday.
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
CSI605 perl. Perl Facts Perl = Pathologically Eclectic Rubbish Lister Perl is highly portable across many different platforms and operating systems Perl.
2000 Copyrights, Danielle S. Lahmani Foreach example = ( 3, 5, 7, 9) foreach $one ) { $one*=3; } is now (9,15,21,27)
The Scripting Programming Language
Dept. of Animal Breeding and Genetics Programming basics & introduction to PERL Mats Pettersson.
Introduction to Programming the WWW I CMSC Winter 2003 Lecture 17.
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
Perl Subroutines User Input Perl on linux Forks and Pipes.
Built-In Functions. Notations For each function, I will give its name and prototype. –prototype = number and type of arguments ARRAY means an actual named.
Perl Variables: Array Web Programming.
Control Structures: for & while Loops
Pemrosesan Teks Herika Hayurani Sept 19, 2006
Programming Perls* Objective: To introduce students to the perl language. Perl is a language for getting your job done. Making Easy Things Easy & Hard.
Presentation transcript:

Perl Programming WeeSan Lee

Roadmap How to Create a Perl Script? Here Documents Three basic data types: Scalars, Arrays, Hashes Branching Iterations File IO Function/Subroutine String Manipulation Regular Expression

How to Create a Perl Script? Edit hello.pl  #!/usr/bin/perl  print "Hello World!\n"; Make hello.pl an executable  $ chmod +x hello.pl Run hello.pl  $./hello.pl Hello World!

Here Documents #!/usr/bin/perl print <<EOF; Hello World! EOF

Scalar Variables $a = 1; $a = 1 + 2; $a = 2 ** 10; $a++; $a--; $a = "foo"; $b = "bar"; $c = $a. $b; $d = $a x 3; print $d; print "$a $b"; $a=`date`; print "$a\n";

Comparisons Numbers  $a == $b# Is $a numerically equal to $b?  $a != $b  $a < $b  $a <= $b  $a > $b  $a >= $b Strings  $a eq $b# Is $a string-equal to $b?  $a ne $b# Is $a string-unequal to $b?

= ("apples", "oranges"); print "$fruit[0]\n";  apples "banana"); print $fruit[2]. "\n";  banana $a = print $a  banana $len print $len  2 $str = print $str  apples oranges $" = "/"; print  apples/oranges ($a, $b) print "$a - $b\n";  apples - oranges print "last index = $#fruit\n";  last index = 1 $#fruit = 0;  apples

is a special array  $ARGV[0]: 1 st command-line argument  $ARGV[1]: 2 nd command-line argument  …

Hashes/Associative Arrays %scores = ("Alice", 80, "Bob", 90, "Claire", 92, "David", 60); print "The score for Claire = $scores{'Claire'}\n"; %scores = ("Alice" => 80, "Bob" => 90, "Claire" => 92, "David" => 60); print "The score for Claire = $scores{Claire}\n";

Hashes/Associative Arrays foreach $i (keys %scores) { print "The score for $i = $scores{$i}\n"; }  The score for Bob = 90  The score for Claire = 92  The score for Alice = 80  The score for David = 60 print "\nAll the scores are:"; for $i (values %scores) { print " $i"; } print "\n\n";  All the scores are:

Hashes/Associative Arrays How to display all sorted by the students?  for $i (sort keys %scores) {  printf("%10s: %d\n", $i, $scores{$i}); }} Alice: 80 Bob: 90 Claire: 92 David: 60

How to display all sorted by the scores?  for $i (sort { $scores{$b} $scores{$a} } keys %scores) {  printf("%10s: %d\n", $i, $scores{$i}); }} Claire: 92 Bob: 90 Alice: 80 David: 60 Hashes/Associative Arrays A subroutine for the sort function. $a and $b are the elements to be compared. is a special 3-way numeric comparison. Eg. 3 1 returns returns returns -1

Hashes/Associative Arrays while (($person, $score) = each(%scores)) { print "The score for $person = $score\n"; }  The score for Bob = 90  The score for Claire = 92  The score for Alice = 80  The score for David = 60

Hashes/Associative Arrays exists() can be used to check the existence of a hash key  If (!exists($scores{weesan})) {  print "No score for weesan\n";  } %ENV is a special hash variable  print "$ENV{USER} is using $ENV{SHELL}\n"; weesan is using /bin/tcsh

Arrays vs. Hashes = ( 0 ); %a = ( 0 => 1 ); print "\$a[0] = $a[0], \$a{0} = $a{0}\n";  What’s the output?  $a[0] = 0, $a{0} = 1

Branching - if Syntax  if ( ) {   } elsif ( ) {   } else {   } Example  if (!$a) {  print "Empty string\n";  } elsif (length($a) == 1) {  print "Len = 1\n";  } elsif (length($a) == 2) {  print "Len = 2\n";  } else {  print "Len > 2\n"; }}

Branching - unless Syntax  unless ( ) {   } else {   } Example  unless ($my_grade >= 60) {  print "I failed CS183!\n";  } else {  print "I passed CS183!\n";  }

Branching - switch or not? $_ = ; chop($_); SWITCH: { /[a-z]/ && do { print "$_ is a lower case.\n"; last SWITCH; }; /[A-Z]/ && do { print "$_ is a upper case.\n"; last SWITCH; }; /[0-9]/ && do { print "$_ is a number.\n"; last SWITCH; }; print "$_ is a punctuation.\n" }

for loop Syntax  for ( ) {   } Examples  for ($i = 0; $i < 10; ++$i) {  print "$i\n";  } Syntax  foreach ( ) {  }} Example  foreach $i (0..7, 8, 9) {  print "$i\n"; }}  foreach $i {  print "$i\n"; }} Range operator

while loop Syntax  while ( ) {  }} Example  print "Password? ";# Ask for input  $a = ;# Get input  chop $a;# Remove the newline  while (lc($a) ne "weesan") {  print "sorry. Again? ";# Ask again  $a = ;# Get input again  chop $a;# Chop off newline again }} Lower case function Chop off the last char. of a string regardless. chomp() remove the trailing \n.

until loop Syntax  until ( ) {  }} Example  print "Password? ";# Ask for input  $a = ;# Get input  chop $a;# Remove the newline  until (lc($a) eq "weesan") {  print "sorry. Again? ";# Ask again  $a = ;# Get input again  chop $a;# Chop off newline again }}

do … while loop Syntax  do {   } while ( ); Examples  do {  print "Password? ";# Ask for input  $a = ;# Get input  chop $a;# Chop off newline  } while (lc($a) ne "weesan");# Redo while wrong input

File IO #!/usr/bin/perl $file = '/etc/passwd'; open(PASSWD, $file) or die "Failed to open $file: = ; close(PASSWD); Open the file and assign the file handle to PASSWD. $! returns the error string. Read everything into an array. Close the file. Similar to || in Bash. Print the whole array.

File IO #!/usr/bin/perl $file = '/etc/passwd'; open(PASSWD, $file) or die "Failed to open $file: $!\n"; foreach $line ( ) { print $line; } close(PASSWD); Read one line at a time. Print one line at a time.

File IO open(INFO, $file);# Open for input open(INFO, ">$file");# Open for output open(INFO, ">>$file");# Open for appending open(INFO, "<$file");# Also open for input open(INFO, '-');# Open standard input open(INFO, '>-');# Open standard output print INFO "This line goes to the file.\n";

File IO Useful trick = ("-")  open(LOG, $ARGV[0]) or  die "Failed to open $ARGV[0]: $!\n";

Function/Subroutine #!/usr/bin/perl sub foo { print "foo()\n"; } # Older version requires & &foo;

Function/Subroutine #!/usr/bin/perl sub bar { print print "1st argument = $_[0]\n"; } bar("1", "2", "3"); bar(1, 2, "3", 4); bar();

Function/Subroutine #!/usr/bin/perl sub max { if ($_[0] > $_[1]) { $_[0];# return is optional } else { $_[1]; } #return ($_[0] > $_[1] ? $_[0] : $_[1]); } $i = max(3, 1); print "$i\n";

Function/Subroutine sub foo { $a = 2; } $a = 1; print "\$a = $a\n"; foo(); print "\$a = $a\n";  $a = 1  $a = 2 sub bar { my $a = 2; } $a = 1; print "\$a = $a\n"; bar(); print "\$a = $a\n";  $a = 1

Function/Subroutine #!/usr/bin/perl $labs = 98; $projects = 91; $ave = int(compute_grade($labs, $projects)); print "Labs = $labs, Projects = $projects, ", "Ave. = $ave (extra credit included)\n"; sub compute_grade { my ($labs, $projects) # With extra credit $labs += 2; my ($total, $ave); $total = $labs + $projects; $ave = ($labs + $projects) / 2; return ($ave); } A good way of using formal parameters inside a Perl function. Local variables declaration.

Function/Subroutine $ man perlsub $ man perlfunc

String Manipulation - substr #!/usr/bin/perl $a = "Welcome to Perl!\n"; print substr($a, 0, 7), "\n";# "Welcome" print substr($a, 7), "\n";# " to Perl!\n" print substr($a, -6, 4), "\n";# "Perl"

String Manipulation - split #!/usr/bin/perl $a = "This is a = split(/ /, $a); = split(/ /, $a, 2);# 2 strings only, ie. “This” and “is a test” foreach $i { print "$i\n"; } $_ = "This is a = split(/ /);# Take $_ as input foreach $i { print "$i\n"; }

String Manipulation - join = ( "This", "is", "a", "test"); $b = join(' $c = join(' / print "\$b = $b\n"; print "\$c = $c\n";  $b = This is a test  $c = This / is / a / test

String Manipulation - substitution #!/usr/bin/perl $a = "I love Perl!"; if ($a =~ s/love/hate/) { print "New \$a = $a\n"; } else { print "Not found!\n"; } $_ = $a; if (s{hate}{love}) { print "New \$_ = $_\n"; } else { print "Not found!\n"; }  New $a = I hate Perl!  New $_ = I love Perl! #!/usr/bin/perl $url = " $url =~ s{/$}{/index.html}; print "$url\n"; 

String Matching Using Regular Expression (Regexp) #!/usr/bin/perl $a = "This is a test"; if ($a =~ /is/) { print "Found!\n"; } else { print "Not Found!\n"; } $_ = $a; if (/is/) { print "Found!\n"; } else { print "Not Found!\n"; }

Regular Expression - Metacharacters.# 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 Eg. /^ /^ /^

Regular Expression - Metasymbols \d# [0-9] \w# [0-9a-zA-Z_] \s# [ \t\r\n] \D# Reverse of \d or [^0-9] \W# Reverse of \w or [^0-9a-zA-Z_] \S# Reverse of \s or [^[ \t\r\n]

Regular Expression - Metasymbols unless ($phone =~ /\d\d\d-\d\d\d\d/) { print "That's not a phone number!\n"; } unless ($phone =~ /\d{3}-\d{4}/) { print "That's not a phone number!\n"; } /\d{3,5}/# 3-5 digits long unless ($passwd =~ /\w{8,}/) { print "Passwd too short!\n"; }

Regular Expression - Captured Strings Also called backreferences, eg.  $a = "07/Jul/2007:08:30:01";  $a =~ /([^:]+):(.+):(.+):(.+)/;  ($hour, $min, $sec) = ($2, $3, $4);  print "$hour:$min:$sec\n";

Regular Expression - is Greedy $a = " "; $a =~ /(1.*0)/; print "$1\n";  $a =~ /(1.*?0)/; print "$1\n"; 

Regular Expression - Misc To ignore case when matching  /\w+/i More info  $ man perlre  

Debug Perl $ perl -w debug.pl $ perl -d debug.pl print() or printf() is your friend

References Programming Perl  Ch 2-5 Beginner's Introduction to Perl  Perl Tutorial 