PERL Part 3 1.Subroutines 2.Pattern matching and regular expressions.

Slides:



Advertisements
Similar presentations
Chapter 25 Perl and CGI (Common Gateway Interface)
Advertisements

Copyright © 2003 Pearson Education, Inc. Slide 6a-1 The Web Wizards Guide to PHP by David Lash.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
1 *Copyright © 2002 Pearson Education, Inc.. 2 Web Wizard’s Guide to CGI/Perl David Lash Chapter 3 Perl Basics.
COS 381 Day 19. Agenda  Assignment 5 Posted Due April 7  Exam 3 which was originally scheduled for Apr 4 is going to on April 13 XML & Perl (Chap 8-10)
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Scripting Languages Chapter 8 More About Regular Expressions.
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
UNIX Filters.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
Slide 6a-1 CHAPTER 6 Matching Patterns: Using Regular expressions to match patterns.
Regular Expression A regular expression is a template that either matches or doesn’t match a given string.
Regular Expressions in ColdFusion Applications Dave Fauth DOMAIN technologies Knowledge Engineering : Systems Integration : Web.
Lesson 3 – Regular Expressions Sandeepa Harshanganie Kannangara MBCS | B.Sc. (special) in MIT.
1 Chapter 6 – Creating Web Forms and Validating User Input spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
Programming Perl in UNIX Course Number : CIT 370 Week 4 Prof. Daniel Chen.
Computer Programming for Biologists Class 5 Nov 20 st, 2014 Karsten Hokamp
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
Chapter 2 Overview of C Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
USING PERL FOR CGI PROGRAMMING
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
ASP.NET Programming with C# and SQL Server First Edition Chapter 5 Manipulating Strings with C#
Input, Output, and Processing
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.
Introduction to Programming the WWW I CMSC Summer 2004 Lecture 13.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Regular Expressions.
CS 330 Programming Languages 10 / 07 / 2008 Instructor: Michael Eckmann.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
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.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 24 The String Section.
Chapter 9: Perl (continue) Advanced Perl Programming Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
When you read a sentence, your mind breaks it into tokens—individual words and punctuation marks that convey meaning. Compilers also perform tokenization.
Copyright © 2003 Pearson Education, Inc. Slide 6a-1 The Web Wizard’s Guide to PHP by David Lash.
Computer Programming for Biologists Class 3 Nov 13 th, 2014 Karsten Hokamp
CS 330 Class 9 Programming plan for today: More of how data gets into a script Via environment variables Via the url From a form By editing the url directly.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
 2001 Prentice Hall, Inc. All rights reserved. Chapter 7 - Introduction to Common Gateway Interface (CGI) Outline 7.1Introduction 7.2A Simple HTTP Transaction.
Introduction to Programming the WWW I CMSC Winter 2004 Lecture 12.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607.
Copyright © 2003 Pearson Education, Inc. Slide 6a-1 The Web Wizard’s Guide to PHP by David Lash.
Prof. Alfred J Bird, Ph.D., NBCT Door Code for IT441 Students.
Introduction to Programming the WWW I CMSC Winter 2004 Lecture 13.
8 1 String Manipulation CGI/Perl Programming By Diane Zak.
ORAFACT Text Processing. ORAFACT Searching Inside Files grep - searches for patterns within files grep [options] [[-e] pattern] filename [...] -n shows.
-Joseph Beberman *Some slides are inspired by a PowerPoint presentation used by professor Seikyung Jung, which was derived from Charlie Wiseman.
Dept. of Animal Breeding and Genetics Programming basics & introduction to PERL Mats Pettersson.
1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental Variables and Functions.
Introduction to Programming the WWW I CMSC Winter 2003 Lecture 17.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Linux Administration Working with the BASH Shell.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 18 The HTML Tag
Regular Expressions.
Chapter 7 - Introduction to Common Gateway Interface (CGI)
String Methods Programming Guides.
CS 330 Class 7 Comments on Exam Programming plan for today:
Chapter 6 JavaScript: Introduction to Scripting
Chapter 8 – Regular Expressions
Lecture 19 Strings and Regular Expressions
Revision Lecture
The Selection Structure
Organization of Programming Languages
Chapter 19 PHP Part II Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
Pattern Matching in Strings
Data Manipulation & Regex
JavaScript: Introduction to Scripting
The Selection Structure
Presentation transcript:

PERL Part 3 1.Subroutines 2.Pattern matching and regular expressions

(1) Subroutines Subroutines provide a way for programmers to group a set of statements, set them aside, and turn them into mini-programs within a larger program. These mini-programs can be executed several times from different places in the overall program

Working with Subroutines You can create a subroutine by placing a group of statements into the following format: sub subroutine_name { set of statements } For example a outputTableRow subroutine sub outputTableRow { print ‘ One Two ’; } Execute the statements in this subroutine, by preceding the name by an ampersand: &outputTableRow;

Subroutine Example Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html( 'Subroutine Example' ); 4. print 'Here is simple table '; 5. &outputTableRow; 6. &outputTableRow; 7. &outputTableRow; 8. print ' ', end_html; 9. sub outputTableRow { 10. print ' One Two '; 11. }

Would Output The Following …

(2) Pattern matching and regular expressions Use Perl pattern matching and regular expressions to filter input data Work with files to enable a program to store and retrieve data

Patterns in String Variables Many programming problems require matching, changing, or manipulating patterns in string variables. –An important use is verifying input fields of a form helps provide security against accidental or malicious attacks. For example, if expecting a form field to provide a telephone number as input, your program needs a way to verify that the input comprises a string of seven digits.

Four Different Constructs –The match operator enables your program to look for patterns in strings. –The substitute operator enables your program to change patterns in strings. –The split function enables your program to split strings into separate variables based on a pattern. –Regular expressions provide a pattern matching language that can work with these operators and functions to work on string variables.

The Match Operator The match operator is used to test if a pattern appears in a string. –It is used with the binding operator (“ =~ ”) to see whether a variable contains a particular pattern.

Other Delimiters? Slash (“/”) is most common match pattern –Others are possible, For example, both use valid match operator syntax: –if ( $name =~ m!Dave! ) { – if ( $name =~ m ) { The reverse binding operator test if pattern is NOT found: if ( $color !~ m/blue/ ) {

Substitutes Substitutes the first occurrence of the search pattern for the change pattern in the string variable. For example, the following changes the first occurrence of t to T : $name = “tom turtle”; $name =~ s/t/T/; print “Name=$name”; The output of this code would be Name=Tom turtle

Changing All Occurrences You can place a g (for global substitution) at the end of the substitution expression to change all occurrences of the target pattern string in the search string. For example, –$name = “tom turtle”; –$name =~ s/t/T/g; –print “Name=$name”; The output of this code would be –Name= Tom TurTle

Using Translate A similar function is called tr (for “translate”). Useful for translating characters from uppercase to lowercase, and vice versa. –The tr function allows you to specify a range of characters to translate from and a range of characters to translate to. : $name="smokeY"; $name =~ tr/[a-z]/[A-Z]/; print "name=$name"; Would output the following Name=SMOKEY

The Alternation Operator Alternation operator looks for alternative strings for matching within a pattern. –(That is, you use it to indicate that the program should match one pattern OR the other). The following shows a match statement using the alternation operator (left) and some possible matches based on the contents of $address (right); this pattern matches either com or edu.

Parenthesis For Groupings You use parentheses within regular expressions to specify groupings. For example, the following matches a $name value of Dave or David. Match Statement: if ( $name =~ /Dav(e|id)/) { print “$name came home from school\n”; }

Example Alternation Operator

Using Regular Expressions regular expressions to enable programs to more completely match patterns. –They actually make up a small language of special matching operators that can be employed to enhance the Perl string pattern matching.

Special Character Classes Perl has a special set of character classes for short hand pattern matching For example consider these two statements if ( $name =~ m/ / ) { if ($name =~ m/\s/ ) {

Special Character Classes

Special Character Classes - II

Special Character Classes - III

Setting Specific Patterns w/ Quantifiers Character quantifiers let you look for very specific patterns For example, use the dollar sign (“ $ ”) to to match if a string ends with a specified pattern. if ($ Name =~ /Jones$/ ) { Matches “John Jones” but not “Jones is here” would not. Also, “The guilty party is Jones” would matches.

Selected Perl Character Quantifiers

Building Regular Expressions that Work 1. Determine the precise field rules. 2. Get form and form-handling programs working 3. Start with the most specific term possible. 4. Anchor and refine. (Use ^ and $ when possible) – if ( $date =~ m{^\d\d/\d\d/\d\d\d\d$} ) { Starts with 2 digits in middle Ends with 4 digits

Regular Expression Special Variables Perl regexs set several special scalar variables: –$& will be equal to the first matching text –$` will be the text before the match, and –$’ will be the text after the first match. $name='*****Marty'; if ( $name =~ m/\w/ ) { print “match at=$& "; print "B4=$` after=$'"; } else { print "Not match"; } Output: match at=M B4=***** after=arty

Drivedate4.pl Example Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html('Date Check'); 4. $date=param('udate'); 5. if ( $date =~ m{^\d\d/[0-3]\d/2\d\d\d$} ) { 6. print 'Valid date=', $date; 7. } else { 8. print 'Invalid date=', $date; 9. } 10. print end_html;

Output...

A Pattern Matching Example 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html('Command Search'); 'XX1234', 'XX1892', 'XX9510'); 5. $com=param('command'); 6. $prod=param('uprod'); 7. if ($com eq "ORDER" || $com eq "RETURN") { 8. $prod =~ s/xx/XX/g; # switch xx to XX 9. if ($prod =~ /XX/ ) { 10. foreach $item ) { 11. if ( $item eq $prod ) { 12. print "VALIDATED command=$com prodnum=$prod"; 13. $found = 1; 14. } 15. } 16. if ( $found != 1 ) { 17. print br,"Sorry Prod Num=$prod NOT FOUND"; 18. } 19. } else { 20. print br, "Sorry that prod num prodnum=$prod looks wrong"; 21. } 22. } else { 23. print br, "Invalid command=$com did not receive ORDER or RETURN"; 24. } 25. print end_html;

Output...

The Split Function split() breaks a string into different pieces based on a field separator. 2 arguments: – a pattern to match (which can contain regular expressions) – and a string variable to split. (into as many pieces as there are matches for the pattern)

split() Example $line = “Please, pass = split( /\s+/, $line ); Sets list variable $result with the following: $result[0] = “Please”; $result[1] = “,” $result[2] = “pass”; $result[3] = “thepepper”; 1 or more spaces Variable to split Results into a list

Another split() Example Another split() example: $ line = “Baseball, hot dogs, apple = split( /,/, $line ); print These lines will have the following output: –newline= Baseball hot dogs apple pie

The Split Function When you know how many matches to expect: $line = “AA1234:Hammer:122:12”; ($partno, $name, $id, $cost) = split( /:/, $line ); print “Part#: $partno; Name: $part; ID: $num; Cost: $cost”; Would output the following: P art#: AA1234; Name: Hammer; ID: 122; Cost: 12

Summary –Perl supports a set of operators and functions that are useful for working with string variables and verifying input data. The match operator, the substitute operator, the translate operator, the split function. –Perl uses regular expressions to to enable a program to look for specific characters (such as numbers, words, or letters) in specific places in any string. You can use them to verify form input, thereby providing a first line of defense against accidental or malicious input.

The End