CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.

Slides:



Advertisements
Similar presentations
Adv. UNIX:Perl/81 Advanced UNIX v Objectives of these slides: –introduce Perl (version ) –mostly based on Chapter 1, Learning Perl
Advertisements

● Perl reference
CSC 4630 Perl 1. Perl Practical Extraction and Support Language A glue language under UNIX Written by Larry Wall Claimed to be the most portable of scripting.
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.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
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.
Scalar Variables Start the file with: #! /usr/bin/perl –w No spaces or newlines before the the #! “#!” is sometimes called a “shebang”. It is a signal.
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
PERL Part 3 1.Subroutines 2.Pattern matching and regular expressions.
CS 898N – Advanced World Wide Web Technologies Lecture 10: Examples of PERL and CGI Chin-Chih Chang
Perl Lecture #1 Scripting Languages Fall Perl Practical Extraction and Report Language -created by Larry Wall -- mid – 1980’s –needed a quick language.
I/O while ($line= ){ #remove new line char \n chomp($line); if($line eq “quit”){ exit(1); } while ( ){ #remove new line char \n chomp($_); if($_ eq “quit”){
Guide To UNIX Using Linux Third Edition
 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.
Computer Programming for Biologists Class 2 Oct 31 st, 2014 Karsten Hokamp
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
1 Operating Systems Lecture 3 Shell Scripts. 2 Shell Programming 1.Shell scripts must be marked as executable: chmod a+x myScript 2. Use # to start a.
1 Operating Systems Lecture 3 Shell Scripts. 2 Brief review of unix1.txt n Glob Construct (metacharacters) and other special characters F ?, *, [] F Ex.
Introduction to Perl Practical Extraction and Report Language or Pathologically Eclectic Rubbish Lister or …
Introduction to Perl & BioPerl Dr G. P. S. Raghava Bioinformatics Centre Bioinformatics Centre IMTECH, Chandigarh Web:
Computer Programming for Biologists Class 5 Nov 20 st, 2014 Karsten Hokamp
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
Introduction To Perl Susan Lukose. Introduction to Perl Practical Extraction and Report Language Easy to learn and use.
Linux+ Guide to Linux Certification, Third Edition
UNIX Shell Script (1) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology
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.
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.
1 Perl Syntax: control structures Learning Perl, Schwartz.
Introduction to Perl Yupu Liang cbio at MSKCC
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
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 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
Algorithms  Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
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”
5 1 Data Files CGI/Perl Programming By Diane Zak.
A Stroll through Perl (R L Schwartz & T Christiansen, O’Reilly) PERL = Practical Extraction and Report Language. A major strength of Perl is the recognition.
CS 330 Programming Languages 10 / 02 / 2007 Instructor: Michael Eckmann.
LIN Unix Lecture 5 Unix Shell Scripts. LIN Command Coordination ; && || command1 ; command2 Interpretation: Do command 1. Then do command.
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,
A Few More Functions. One more quoting operator qw// Takes a space separated sequence of words, and returns a list of single-quoted words. –no interpolation.
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.
PERL By C. Shing ITEC Dept Radford University. Objectives Understand the history Understand constants and variables Understand operators Understand control.
Perl Scripting II Conditionals, Logical operators, Loops, and File handles Suzi Lewis Genome Informatics.
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
2000 Copyrights, Danielle S. Lahmani Foreach example = ( 3, 5, 7, 9) foreach $one ) { $one*=3; } is now (9,15,21,27)
Perl Chapter 3 Conditional statements. Control Expressions Control expressions – interpreted as T/F (evaluated as strings or numbers) – simple, relational,
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.
CPTG286K Programming - Perl Chapter 9: Misc. Control Structures Chapter 10: Filehandles & File tests.
CS 330 Programming Languages 09 / 30 / 2008 Instructor: Michael Eckmann.
Perl Subroutines User Input Perl on linux Forks and Pipes.
Linux Administration Working with the BASH Shell.
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
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.
Introduction to Bash Programming, part 3
Presentation transcript:

CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin

Course Objectives Learn to program in Perl Use effective documentation techniques Use clear programming style

Lecture 1 Outline Hello world program Storing keyboard input into a scalar variable If-then-else string comparison Storing and accessing arrays Else if blocks Storing and accessing hashes

Important UNIX commands Use the pico editor to create PERL scripts: $ pico ex1.pl Make sure PERL scripts have execute permissions $ chmod +x ex1.pl Run PERL scripts by typing its full name $ ex1.pl

Hello, world! # This is the standard Hello, world! program # Call the PERL compiler using -w (warning) switch #!/usr/bin/perl -w print (“Hello, world!\n”);

Storing input from the keyboard Get keyboard input with the construct Store input in a scalar variable called $name Ex1.pl: #!/usr/bin/perl -w print “What is your name?”;# produce prompt $name = ;# read keyboard chomp ($name);# rid trailing newline print “Hello, $name!\n”;# print output

If-then-else string comparison Statement blocks appear within curly brackets { } Use the eq operator to compare equality of two strings, and ne to determine inequality Use clear indentation style DO NOT put curly brackets in comment: if ($name eq “Randal”) { # this end of block is never read }

If-then-else comparison example Ex2.pl: #!/usr/bin/perl -w print “What is your name?”;# produce prompt $name = ;# read keyboard chomp ($name);# rid trailing newline if ($name eq “Randal”) { print “Hello, Randal! How good of you to be here!\n”; } else { print “Hello, $name!\n”; }# ordinary greeting NOTE. The following DOES NOT work (why?): { print “Hello, $name!\n”; # ordinary greeting }

Arrays in PERL Each element of an array stores scalar variables Array variable names start with during assignment. For = (“camel”, “llama”, “alpaca”); Use the qw() operator to quote words in an array. For = qw(camel llama alpaca);

Accessing PERL arrays Elements of an array are accessed as scalar variables: –$words[0] is camel –setting $i to 2, $words[$i] is alpaca

If-then-elsif-else block Note that an else if block is spelled elsif: if ($words[$i] eq $guess) # is guess correct? { $correct = “yes”;# guess is correct } elsif ($i < 2)# more words to look at? { $i = $i + 1;# increment $i } else { print “Wrong, try again. What is the secret word?”; $guess = ;# read keyboard chomp ($guess);# rid trailing newline $i = 0; }

Storing tables in a Hash Hashes hold scalar values referenced by a key Hash variables start with a % during assignment. For example: %words = qw( fredcamel barneyllama bettyalpaca wilmaalpaca );

Accessing table data in a Hash Hash data elements are accessed as scalar variables, and addressed with curly brackets: – $words{“betty”} is alpaca –setting $person to betty, $words{$person} is alpaca

Lecture 2 Outline String operations –Pattern match operator –Substitution operator –Translation operator What Is Truth? Subroutines Filehandles

String Operations Pattern match operator –Use the =~ operator to match strings –Use slashes to make sure white/spaces are significant –Use ^ to specify a “start with” pattern –Use \b to denote word boundary –Use /i to ignore case

Pattern Matching Example Ex3.pl #!/usr/bin/perl #Turn off warning: notice no –w switch […rest of program deleted …] chomp ($name); # rid trailing newline If ($name =~ /^randal\b/i)# Match names starting # with randal, use word # boundary, and ignore case { print “Hello, Randal! How good of you to be here!\n”; } […rest of program deleted …]

String Operations (cont’d) Substitution operator –Use the s operator to perform substitutions delimited by slashes –Regular expressions specify from and to what the operator will substitute. From and to entries are separated by a slash

Substitution example To substitute a string with another that doesn’t contain non-word characters –\W specifies all non-word characters –.* specifies characters to the end of string –A blank “to” entry substitutes all “from” entries –The following finds the first non-word character in $name, and substitutes them with blanks to the end of string $name =~ s/\W.*//;

String Operations (cont’d) Translation operator –Use the tr operator to perform translations delimited by slashes –Regular expressions specify from and to what the operator will translate. From and to entries are separated by a slash

Translation example To translate a list of uppercase characters into lowercase: –Specify the A-Z list in the “from” entry –Specify the a-z list in the “to” entry –The following turns any uppercase characters in $name into lowercase characters $name =~ tr/A-Z/a-z/;

What Is Truth? In PERL: –Any string is true except for “” and “0” –Any number is true except 0 –Any reference is true –Any undefined value is false From “Programming Perl” 3 rd Edition Page 29-30

Subroutines Defined using sub subroutine_name { } The my() operator defines private parameters stored in local array Subroutines return values using the return statement

Subroutine example sub good_word { my($somename, $someguess) # name of parameters $somename =~ s/\W.*//; # remove everything # after first word $somename =~ tr/A-Z/a-z/; # lowercase everything if ($someone eq “randal”) { return 1; }# return true elsif (($words{$someone} || “groucho”) eq $someguess { return 1; }# return true else { return 0; }# return false }

Filehandles Create user-defined filehandles to access files Use the open() function to assign a filehandle to a file Access file contents by assigning the scalar variable a filehandle value Close the file with the close() operator

Filehandle example sub init_words { open(WORDSLIST, “wordslist”); while ($name = ) # read name { chomp ($name);# rid trailing newline $word = ;# read word chomp ($word); # rid trailing newline $words{$name} = $word;# Put into hash table } close (WORDSLIST);# close file }

Lecture 3 Outline Checking age of files Sending warnings Reading the next file Formatting output Renaming files Saving hash tables into a database Retrieving information from a database

Checking the age of files Assign a filehandle to a file for examination Use the –M file test operator to check the age of the file Compare the filehandle to the number of days

File age checking example sub init_words { open (WORDSLIST, “wordslist”) ||# open file or die “Can’t open wordlist: $!”;# exit & print error if (-M WORDSLIST >= 7.0)# is age of file >= 7 days? {# print error and exit die “Sorry, the wordslist is older than seven days.”; } while ($name = ) # read name { chomp ($name);# rid trailing newline $word = ;# read word chomp ($word); # rid trailing newline $words{$name} = $word;# put into hash table } close (WORDSLIST) || # close file or die “Couldn’t close wordlist: $!”;# print error and exit }

Sending warnings Use the open() function to create a filehandle to the MAIL process Pipe your address into the MAIL process Write message into the MAIL process Close filehandle to the MAIL process

Example sending warning sub good_word { my($somename, $someguess) of parameters […rest of program deleted…] else {# mail open MAIL, “|mail # write text of print MAIL “Warning: $someone guessed $someguess\n”; close MAIL;# close MAIL filehandle return 0;# return value is false }

Reading the next file The glob function returns the next filename that matches a search pattern Put the glob function in a while loop to list all files in a directory

Example of reading next files sub init_words { while ( defined ($filename = glob(“*.secret”)) ) {# find next file until undef open (WORDSLIST, $filename) ||# open file or die “Can’t open wordlist: $!”;# print error, exit if (-M WORDSLIST < 7.0)# complement test { while ($name = ) {# read until undef chomp $name;# rid trailing newline $word = ;# get word chomp $word; # rid trailing newline $words{name} = $word;# put into table } close (WORDSLIST) || die “Couldn’t close wordlist: $!”; }

Formatting output The format statement is used to layout reports by formatting output variables A single write; command is used execute a report Formats definitions contain a format name, and a template definition Template definitions contain fieldlines and fieldholders

Format definition example format @<<<<<<<<<<<< $filename, $name, $word. format STDOUT_TOP = $% Filename Name Word =============== ========= =============.

Sample Output Page 1 Filename Name Word =============== ========= ============= barney.secret christina rabbit barney.secret joey fish barney.secret jennifer jellyfish fred.secret fred camel fred.secret barney llama fred.secret betty alpaca fred.secret wilma alpaca

Renaming files Use the rename function to alter the name of files When used in conjunction with a check for the age of next files, older files can be automatically renamed

Example renaming expired files sub init_words { while ( defined($filename = glob("*.secret")) ) { open(WORDSLIST, $filename) || die "Can't open wordlist: $!"; if (-M WORDSLIST < 7.0) { […rest of program deleted…] } else { rename ($filename,"$filename.old") || die "can't rename $filename to $filename.old: $!"; } close (WORDSLIST) || die "Couldn't close wordlist: $!"; }

Saving hash tables in a database The dbmopen() statement can create a hash table that stores information on a database file Information is stored into the hash table by assigning values for a key The dbmclose() statement disconnects the hash from the database file

Saving hash table data example […the following goes at the end of the main section of Ex3.pl…] # log all successful accesses # last_good hash contains successful accesses dbmopen (%last_good,”lastdb”,0666); $last_good{$name} = time; dbmclose(%last_good);

Retrieving info from database Use the dbmopen() statement to get hash table data from database file Use a foreach loop to process each entry (key) from the database file. Use the sort and keys functions to produce a sorted list Store and calculate result from hash into scalar variable Execute report using a write; statement

Example retrieving database info Ex4.pl #!/usr/bin/perl dbmopen (%last_good,"lastdb",0666);# open lastdb using # 0666 file permission foreach $name (sort keys %last_good)# process each entry { $when = $last_good{$name};# assign hash data to # scalar variable which # contains data in seconds $hours = (time - $when) / 3600; # compute hours ago write;# execute report } format STDOUT = last correct guess hours ago. $name, $hours.

Sample Output User Betty : last correct guess was 0.01 hours ago. User Denny : last correct guess was 0.09 hours ago. User Fred : last correct guess was 0.09 hours ago. User barney : last correct guess was 0.01 hours ago. User christina : last correct guess was 0.00 hours ago. User jennifer : last correct guess was 0.00 hours ago. User joey : last correct guess was 0.00 hours ago. User wilma : last correct guess was 0.00 hours ago.