Chapter 9: Perl (continue) Advanced Perl Programming Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.

Slides:



Advertisements
Similar presentations
4.1 Reading and writing files. 4.2 Open a file for reading, and link it to a filehandle: open(IN, "
Advertisements

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.
Perl File I/O Learning Objectives: 1. To understand the usage of file handler in Perl 2. To learn the file error handling / testing in Perl.
PERL Part 3 1.Subroutines 2.Pattern matching and regular expressions.
Linux+ Guide to Linux Certification, Second Edition
5.1 Previously on... PERL course (let ’ s practice some more loops)
Perl Basics A Perl Tutorial NLP Course What is Perl?  Practical Extraction and Report Language  Interpreted Language Optimized for String Manipulation.
Guide To UNIX Using Linux Third Edition
C++ for Engineers and Scientists Third Edition
Perl - Advanced More Advanced Perl  Functions  Control Structures  Filehandles  Process Management.
 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.
Subroutines Just like C, PERL offers the ability to use subroutines for all the same reasons – Code that you will use over and over again – Breaking large.
Shell Scripting Awk (part1) Awk Programming Language standard unix language that is geared for text processing and creating formatted reports but it.
CS0007: Introduction to Computer Programming File IO and Recursion.
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
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.
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Linux+ Guide to Linux Certification, Third Edition
Shell Script & Perl Programming Lesson 9. Shell Programming A shell script is a text file that contains Linux (UNIX) commands, which you enter using any.
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.
Agenda Regular Expressions (Appendix A in Text) –Definition / Purpose –Commands that Use Regular Expressions –Using Regular Expressions –Using the Replacement.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
File IO and command line input CSE 2451 Rong Shi.
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.
Working with Forms and Regular Expressions Validating a Web Form with JavaScript.
When you read a sentence, your mind breaks it into tokens—individual words and punctuation marks that convey meaning. Compilers also perform tokenization.
JavaScript, Part 2 Instructor: Charles Moen CSCI/CINF 4230.
Introduction to Unix – CS 21
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
Perl II Part III: Motifs and Loops. Objectives Search for motifs in DNA or Proteins Interact with users at the keyboard Write data to files Use loops.
Computer Programming for Biologists Class 3 Nov 13 th, 2014 Karsten Hokamp
5 1 Data Files CGI/Perl Programming By Diane Zak.
(A Very Short) Introduction to Shell Scripts CSCI N321 – System and Network Administration Copyright © 2000, 2003 by Scott Orr and the Trustees of Indiana.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Artificial Intelligence Lecture No. 26 Dr. Asad Ali Safi ​ Assistant Professor, Department of Computer Science, COMSATS Institute of Information Technology.
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,
1 Lecture 9 Shell Programming – Command substitution Regular expressions and grep Use of exit, for loop and expr commands COP 3353 Introduction to UNIX.
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.
XP New Perspectives on XML, 2 nd Edition Tutorial 7 1 TUTORIAL 7 CREATING A COMPUTATIONAL STYLESHEET.
PERL By C. Shing ITEC Dept Radford University. Objectives Understand the history Understand constants and variables Understand operators Understand control.
Part 4 Arrays: Stacks foreach command Regular expressions: String structure analysis and substrings extractions and substitutions Command line arguments:
Uniq The uniq command is useful when you need to find duplicate lines in a file. The basic format of the command is uniq in_file out_file In this format,
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.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
1 Lecture 8 Shell Programming – Control Constructs COP 3353 Introduction to UNIX.
Shell Scripting March 1st, 2004 Class Meeting 7.
Lecture 9 Shell Programming – Command substitution
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
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 ©
Agenda Control Flow Statements Purpose test statement
Topics Introduction to File Input and Output
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
Pemrosesan Teks Herika Hayurani Sept 19, 2006
Topics Introduction to File Input and Output
Topics Introduction to File Input and Output
Presentation transcript:

Chapter 9: Perl (continue) Advanced Perl Programming Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition

Announcement Quiz on the next class. Sort alphabetically ( sort { $a cmp $b ) grades=(80,100,95); foreach $grade { print "$grade\n" } # output 100, 80, 95 Sort numerically foreach $grade (sort {$a { print "$grade\n" } # output 80, 95, 100 Associative arrays %fruit = ("apples“ => 6, "cherries“ => 8, "oranges“ => 11); $d = 2*$fruit { “apples” } +3* $fruit { “cherries” } ;

Advanced Perl Programming Objectives After studying this lesson, you should be able to: Pattern Matches File operations: open, read/write, close Use Command-Line Arguments as Values Define and use subroutines

Regular Expressions A regular expression (pattern) is a sequence of characters to be searched for in a character string. In Perl, patterns are normally enclosed in slash characters: /def/ Match operator (=~) $result = $var =~ /def/; The result of the =~ operation is one of the following: –A nonzero value, or true, if the pattern is found in the string –0, or false, if the pattern is not matched

Pattern Matches The !~ operator is similar to =~, except that it checks whether a pattern is not matched. $result = $var !~ /abc/; A program that illustrates the use of the matching operator. #!/usr/bin/perl print ("Ask me a question politely:\n"); $question = ; if ($question =~ /please/) { # true if the value stored in $question # contains the word please print ("Thank you for being polite!\n"); } else { print ("That was not very polite!\n"); }

Regular Expressions * and ? The * special character matches zero or more occurrences of the preceding character. /de*f/ matches df, def, deef, and so on. /[eE]*/ matches the empty string as well as any combination of E or e in any order. The ? character matches zero or one occurrence of the preceding character. /de?f/ matches either df or def

Regular Expressions [ ] [ ] special characters enable you to define patterns that match one of a group of alternatives. –For example: /d[eE]f/ matches def or dEf Combine [ ] with + to match a sequence of characters of any length. –For example: d[eE]+f/ matches all of the following: def, dEf, deef, dEef, dEEEeeeEef

Regular Expressions : Escape for Special Characters If you want your pattern to include a character that is normally treated as a special character, precede the character with a backslash \. For example: –To check for one or more occurrences of * in a string, use the following pattern: /\*+/ –To include a backslash in a pattern, specify two backslashes: /\\+/

Regular Expressions : Excluding When the ^ character appears as the first character after the [, it indicates that the pattern is to match any character except the ones displayed between the [ and ]. For example, the pattern /d[^eE]f/ matches any pattern that satisfies the following criteria: –The first character is d. –The second character is anything other than e or E. –The last character is f.

Regular Expressions ^ and $ The pattern anchors ^ ensures that the pattern is matched only at the beginning of a string. /^def/ matches def only if these are the first three characters in the string. The pattern anchors $ ensures that the pattern is matched only at the end of a string. /def$/ matches def only if these are the last three characters in the string. What does /^def$/ mean?

Regular Expressions \b and \B The \b pattern anchor specifies that the pattern must be on a word boundary. –/\bdef/ matches only if def is the beginning of a word. This means that def and defghi match but abcdef does not. –You can also use \b to indicate the end of a word. For example, /def\b/ matches def and abcdef, but not defghi. The \B pattern anchor is the opposite of \b. \B matches only if the pattern is contained in a word. –/\Bdef/ matches abcdef, but not def. –/def\B/ matches defghi. –/\Bdef\B/ matches cdefg or abcdefghi, but not def, defghi, or abcdef The \b and \B pattern anchors enable you to search for words in an input line without having to break up the line using split.

Regular Expressions Usages Conditional Matches using Regular Expressions $dataVariable =~ / please / ; Substitutions using Regular Expressions s/pattern/replacement/options; $pet =~ s/\bcat\b/dog/ig ; # i: case insensitive $userinput =~ s/\n//g ; # remove the new line characters $string =~ s/^\s+// ; # strip leading spaces from a string $string =~ s/\s+$// ; # strip trailing spaces from a string

Advanced Perl Programming Objectives Pattern Matches File operations: open, read/write, close Use Command-Line Arguments as Values Define and use subroutines

How Perl Accesses Disk Files Perl uses filehandles to reference files A filehandle is the name for an I/O connection between your Perl program and the operating system, and it can be used inside your program to open, read, write, and close the file Nearly all program functions are written to return a value that indicates whether the function was carried out successfully

File Open Syntax: open (filehandle, filename); filehandle represents the name you want to use in your Perl program to refer to the file. filename represents the location of the file on your machine. If open returns a nonzero value, the file has been opened successfully. If open returns 0, an error has occurred. if (open(MYFILE, “test.txt")) { # here's what to do if the file opened }

File Open Mode Read mode: (default mode) open (FILE, "test.txt"); Enables the program to read the existing contents of the file but does not enable it to write into the file Write mode: open (FILE, “>test.txt"); Destroys the current contents of the file and overwrites them with the output supplied by the program Append mode: open (FILE, “>>test.txt"); Appends output supplied by the program to the existing contents of the file

Close a File Syntax: close (filehandle); close requires one argument: the file handle representing the file you want to close. Once closed, you cannot read from it or write to it without invoking open again.

Read from a File Syntax: $var = ; A program that reads lines from a file and prints them on the screen. #!/usr/local/bin/perl if ( open(MYFILE, “test.txt") ) { $line = ; # read a line from file while ($line ne "") { # loop until the end of file print ($line); # print on the screen $line = ; # read a line from file } close(MYFILE);

Write to a File Syntax: print filehandle contents; A program that opens two files and copies one into another. #!/usr/local/bin/perl open(INFILE, “test.txt") # open in read mode open(OUTFILE, ">test.txt.bak"); # open in write mode $line = ; while ($line ne "") { print OUTFILE ($line); # write into a file $line = ; } close(INFILE); close(OUTFILE);

A Comprehensive Example A program that tests whether a file exists before opening it for writing. #!/usr/local/bin/perl unless (open(INFILE, "infile")) { die ("Input file cannot be opened.\n"); } if (-e "outfile") { die ("Output file already exists.\n");} unless (open(OUTFILE, ">outfile")) { die ("Output file cannot be opened.\n"); } $line = ; while ($line ne "") { print OUTFILE ($line); $line = ; } close(INFILE); close(OUTFILE);

Advanced Perl Programming Objectives Pattern Matches File operations: open, read/write, close Use Command-Line Arguments as Values Define and use subroutines

Command Line Arguments Perl stores the command-line arguments $ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc An Example, input.pl: #!/usr/bin/perl $numArgs = $#ARGV + 1; print “You gave $numArgs command-line arguments.\n"; foreach $argnum (0.. $#ARGV) { print "$ARGV[$argnum], "; } Running results: $ Input.pl You gave me 4 command-line arguments. 1, 2, 3, 4

Advanced Perl Programming Objectives Pattern Matches File operations: open, read/write, close Use Command-Line Arguments as Values Define and use subroutines

Subroutines In Perl, a subroutine is a separate body of code designed to perform a particular task. A Perl program executes this body of code by calling or invoking the subroutine; the act of invoking a subroutine is called a subroutine invocation. Subroutines serve two useful purposes: –break down your program into smaller parts, making it easier to read and understand. –enable you to use one piece of code to perform the same task multiple times, eliminating needless duplication Definition sub subname { statement_block } Invocation &subname;

Subroutines A program that uses a subroutine. #!/usr/local/bin/perl $total = 0; &getnumbers; foreach $number { $total += $number; } print ("the total is $total\n"); sub getnumbers { $line = ; $line =~ s/^\s+|\s*\n$//g; # removes the leading and trailing white # space (including the trailing newline) # from the input = split(/\s+/, $line); }

Summery Regular Expressions –Conditional matches: =~. !~ –Substitutions: s/pattern/replacement/options; File operations: –Open: open(filehandle, filename) –Read: $line = ; –Write: print filehandle $line; –Close: close(filehandle); Use Command-Line Arguments as Values Define and use subroutines –Define: sub subname { statement_block } –Invocation: &subname;