240-491 Adv. UNIX:Perl/81 Advanced UNIX v Objectives of these slides: –introduce Perl (version 4.0-5.0) –mostly based on Chapter 1, Learning Perl 240-491.

Slides:



Advertisements
Similar presentations
Perl Practical Extration and Reporting Language An Introduction by Shwen Ho.
Advertisements

CST8177 awk. The awk program is not named after the sea-bird (that's auk), nor is it a cry from a parrot (awwwk!). It's the initials of the authors, Aho,
Social Web Design 1 Darby Chang Social Web Design.
Molecular Biomedical Informatics Web Programming 1.
An Introduction to Perl with Applications in Web Page Scraping.
Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
CSCI 1730 April 1 st, Materials Class notes slides & some “plain old” html & source code examples linked from course calendar board notes & diagrams.
A Guide to Unix Using Linux Fourth Edition
1 Perl Syntax: substitution s// and character replacement tr//
The Linux Operating System Lecture 6: Perl for the Systems Administrator Tonga Institute of Higher Education.
● 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.
Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
Second edition Your UNIX: The Ultimate Guide Das © 2006 The McGraw-Hill Companies, Inc. All rights reserved. UNIX – The Master Manipulator perl Perl is.
CSET4100 – Fall 2009 Perl Introduction Scalar Data, Operators & Control Blocks Acknowledgements: Slides adapted from NYU Computer Science course on UNIX.
Introduction to Perl Learning Objectives: 1. To introduce the features provided by Perl 2. To learn the basic Syntax & simple Input/Output control in Perl.
Perl Lecture #1 Scripting Languages Fall Perl Practical Extraction and Report Language -created by Larry Wall -- mid – 1980’s –needed a quick language.
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Lecture 02CS311 – Operating Systems 1 1 CS311 – Lecture 02 Outline UNIX/Linux features – Redirection – pipes – Terminating a command – Running program.
Introduction to Linux and Shell Scripting Jacob Chan.
Shell Scripting Awk (part1) Awk Programming Language standard unix language that is geared for text processing and creating formatted reports but it.
Computer Programming for Biologists Class 2 Oct 31 st, 2014 Karsten Hokamp
Advanced File Processing
Introduction to Shell Script Programming
Introduction to Perl & BioPerl Dr G. P. S. Raghava Bioinformatics Centre Bioinformatics Centre IMTECH, Chandigarh Web:
Agenda User Profile File (.profile) –Keyword Shell Variables Linux (Unix) filters –Purpose –Commands: grep, sort, awk cut, tr, wc, spell.
Chapter Four UNIX File Processing. 2 Lesson A Extracting Information from Files.
Guide To UNIX Using Linux Fourth Edition
Week Three Agenda Administrative Issues Link of the Week Review Week Two Information This Week’s Expected Outcomes Next Lab Assignment Break-Out Problems.
Computer Programming for Biologists Oct 30 th – Dec 11 th, 2014 Karsten Hokamp  Fill out.
Isecur1ty training center Presented by : Eng. Mohammad Khreesha.
CST8177 bash Scripting Chapters 13 and 14 in Quigley's "UNIX Shells by Example"
Topic 1: Welcome CSE2395/CSE3395 Perl Programming.
Chapter Five Advanced File Processing Guide To UNIX Using Linux Fourth Edition Chapter 5 Unix (34 slides)1 CTEC 110.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
Agenda Regular Expressions (Appendix A in Text) –Definition / Purpose –Commands that Use Regular Expressions –Using Regular Expressions –Using the Replacement.
1 Basic Perl CGI Programming. 2 Issues How and when your program is invoked. Generating Response –HTTP Headers –HTML (or whatever document type you want)
Agenda Link of the week Use of Virtual Machine Review week one lab assignment This week’s expected outcomes Review next lab assignments Break Out Problems.
Sed, awk, & perl CS 2204 Class meeting 13 *Notes by Mir Farooq Ali and other members of the CS faculty at Virginia Tech. Copyright 2003.
Introduction to Perl Yupu Liang cbio at MSKCC
Introduction to Unix – CS 21 Lecture 12. Lecture Overview A few more bash programming tricks The here document Trapping signals in bash cut and tr sed.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
Introduction to Unix – CS 21
Computer Programming for Biologists Class 3 Nov 13 th, 2014 Karsten Hokamp
Chapter Five Advanced File Processing. 2 Lesson A Selecting, Manipulating, and Formatting Information.
Chapter Twelve sed, awk & perl1 System Programming sed, awk & perl.
Adv. UNIX: Prelim/01 Advanced UNIX v Who I am: –Andrew Davison CoE, Info. Eng. Research Lab. (Room 101) v Objectives –to.
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.
Lesson 3-Touring Utilities and System Features. Overview Employing fundamental utilities. Linux terminal sessions. Managing input and output. Using special.
– Intermediate Perl 1/6/ Intermediate Perl - POD, parameters and configuration Intermediate Perl – Session 7 · POD –
 2001 Prentice Hall, Inc. All rights reserved. Chapter 7 - Introduction to Common Gateway Interface (CGI) Outline 7.1Introduction 7.2A Simple HTTP Transaction.
CSE S. Tanimoto Perl-Intro - 1 Perl Practical Extraction and Report Language Shell-level scripting language: Glue that ties together programs written.
 History  Ease of use  Portability  Standard  Security & Privacy  User support  Application &Popularity Today  Ten Most Popular Programming Languages.
PERL By C. Shing ITEC Dept Radford University. Objectives Understand the history Understand constants and variables Understand operators Understand control.
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
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.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
Linux Administration Working with the BASH Shell.
CS 330 Class 7 Comments on Exam Programming plan for today:
SUSE Linux Enterprise Desktop Administration
Introduction to Programming the WWW I
PROGRAMMING THE BASH SHELL PART IV by İlker Korkmaz and Kaya Oğuz
Guide To UNIX Using Linux Third Edition
Chapter Four UNIX File Processing.
Introduction to Bash Programming, part 3
Presentation transcript:

Adv. UNIX:Perl/81 Advanced UNIX v Objectives of these slides: –introduce Perl (version ) –mostly based on Chapter 1, Learning Perl Special Topics in Comp. Eng. 1 Semester 2, Introduction to Perl

Adv. UNIX:Perl/82 Overview 1. Starting with Perl 2. I/O 3. If-else 4. while 5. Arrays (lists) continued

Adv. UNIX:Perl/83 6. Handling Varying Input 7. Subroutines 8. File Processing 9. Reporting 10. Using the UNIX DBM Database 11. The Web and Perl

Adv. UNIX:Perl/84 1. Starting with Perl v Practical Extraction and Report Language –Larry Wall, from 1987 v Features combine shell, awk, many UNIX tools, C libraries (all coded in Perl). v Emphasis on string manipulation, table generation, REs, excellent libraries –especially good Internet/Web libraries continued

Adv. UNIX:Perl/85 v On many platforms; free  Many man and info pages.  Many newsgroups (e.g. comp.lang.perl ) v Perl v.5 –OOP, more REs, modules –backward compatible with v.4 –check your version by typing: $ perl -v

Adv. UNIX:Perl/ Books v Learning Perl Randal L. Schwartz & Tom Christiansen O'Reilly, 1997, 2nd ed. v Programming Perl Larry Wall & Randal L. Schwartz O'Reilly, 2000, 3rd ed. –not easy to read, more of a reference text In our library

Adv. UNIX:Perl/ Web Resources v The main Perl site: –current Perl version, documentation, libraries (CPAN), FAQs, tools and utilities, features –reference sections on: u applications (e.g. games, graphics), Web, networking, system admin, etc. continued

Adv. UNIX:Perl/88 v Resources about Perl –e.g. tutorials, manuals, Web-related, recommended books, example scripts – computing/perl.html v A beginner's Guide to Perl –

Adv. UNIX:Perl/ Hello World (hw.pl) $ cat hw.pl #!/usr/bin/perl print "Hello, world!\n"; $ chmod u+x hw.pl $ hw.pl Hello, world! Or: $ perl hw.pl

Adv. UNIX:Perl/ I/O #!/usr/bin/perl # hm.pl print "What is your name? "; $name = ; chop($name); print "Hello, $name!\n"; $ perl hm.pl What is your name? andrew Hello, andrew! $

Adv. UNIX:Perl/ if-else #!/usr/bin/perl # ch.pl print "What is your name? "; $name = ; chop($name); if ($name eq "Randal") { print "Hello, Sir Randal!\n"; } else { print "Hello, $name!\n"; # ordinary }

Adv. UNIX:Perl/ while #!/usr/bin/perl # sword.pl $secretword = "llama"; print "What is your name? "; $name = ; chop($name); if ($name eq "Randal") { print "Hello, Sir Randal!\n"; } : continued Not very secret Guess the secret word

Adv. UNIX:Perl/813 else { print "Hello, $name!\n"; # ordinary print "Secret word? "; $guess = ; chop($guess); while ($guess ne $secretword) { print "Wrong, try again: "; $guess = ; chop($guess); } } $ perl sword.pl What is your name? andrew Hello, andrew! Secret word? foobar Wrong, try again: llama $

Adv. UNIX:Perl/ Arrays = ("camel", "llama", "oyster"); $words[0] is "camel"  List variables begin –$words[0] is a value in the list, so uses $

Adv. UNIX:Perl/815 swords.pl = ("camel", "llama", "oyster"); print "What is your name? "; $name = ; chop($name); if ($name eq "Randal") { print "Hello, Sir Randal!\n"; } : continued Guess the secret word (v.2) An array of secret words

Adv. UNIX:Perl/816 else { print "Hello, $name!\n"; # ordinary print "Secret word? "; $guess = ; chop($guess); $i = 0; # index $correct = "maybe"; # dummy value : continued

Adv. UNIX:Perl/817 while ($correct eq "maybe") { if ($words[$i] eq $guess) { # right? $correct = "yes"; } elsif ($i ; chop($guess); $i = 0; # start words again } } } The user can win by guessing any of the secret words.

Adv. UNIX:Perl/818 Usage $ perl swords.pl What is your name? andrew Hello, andrew! Secret word? foo Wrong, try again: bar Wrong, try again: llama $ one of the secret words

Adv. UNIX:Perl/ Associative Arrays (tables)  PersonSecret Word fredcamel barneyllama bettyoyster wilmaoyster v %words = ("fred", "camel", "barney","llama", "betty", "oyster", "wilma", "oyster");  $words{"betty"} is "oyster"  Associative array variables begin with % –e.g. %words –$words{"betty"} is a value in the list, so uses $

Adv. UNIX:Perl/820 swords2.pl #!/usr/bin/perl %words = ("fred","camel","barney","llama", "betty", "oyster", "wilma", "oyster"); print "What is your name? "; $name = ; chop($name); if ($name eq "Randal") { print "Hello, Sir Randal!\n"; } : continued Each user has their own secret word

Adv. UNIX:Perl/821 else { print "Hello, $name!\n"; # ordinary $secretword = $words{$name}; # get secret word print "Secret word? "; $guess = ; chop($guess); while ($guess ne $secretword) { print "Wrong, try again: "; $guess = ; chop($guess); } }

Adv. UNIX:Perl/822 Usage $ perl swords2.pl What is your name? barney Hello, barney! Secret word? oyster Wrong, try again: foobar Wrong, try again: llama $ barney's secret word!

Adv. UNIX:Perl/ Adding a Default Secret Word... $secretword = $words{$name}; if ($secretword eq "") { # not found! $secretword = "groucho"; } print "Secret word? ";...

Adv. UNIX:Perl/ Handling Varying Input  sword.pl (and others) treats "Randal" in a special way.  But: "Randal L. Schwartz" or "randal" is treated like other users.

Adv. UNIX:Perl/ Replace eq by =~ and RE... if ($name =~ /^Randal/) { # it matches, do something } else { # no match, do something else }... REs are one of the big advantages of Perl

Adv. UNIX:Perl/ Extended REs  Check for a word boundary with \b  Ignore case with the i option (after the last / )

Adv. UNIX:Perl/ if ($name =~ /^randal\b/i) { # matches "Randal...", "ranDAL..." print "Hello, Sir Randal!\n"; } else { # no match, do something else }... Part of final1.pl

Adv. UNIX:Perl/ Substitution and Translation  Substitution: find and replace (like s/../../ in vi ).  Translation: map characters to others (like tr )

Adv. UNIX:Perl/ print "What is your name? "; $name = ; chop($name); $name =~ s/\W.*//; # Get rid of everything # after first word. $name =~ tr/A-Z/a-z/; # Make lowercase. if ($name eq "randal") { print "Hello, Sir Randal!\n"; }... e.g. Dr.Andrew Davison becomes dr

Adv. UNIX:Perl/ Subroutines sub good_word { # used in final1.pl local($somename, $someguess) # input arguments $somename =~ s/\W.*//; $somename =~ tr/A-Z/a-z/; if ($somename eq "randal") 1 # return true } elsif (($words{$somename} || "groucho") eq $someguess) { 1; } else { 0; # return false } } # end of subroutine Not a good feature

Adv. UNIX:Perl/831 Called in final1.pl:... print "Secret word? "; $guess = ; chop($guess); while (! &good_word($name, $guess) ) { print "Wrong, try again: "; $guess = ; chop($guess); } } Don't forget the &

Adv. UNIX:Perl/ File Processing  Read words from the "wordslist" file: sub init_words { # used inside final1.pl open(WORDSLIST, "wordslist"); while ($name = ) { chop($name); $word = ; chop($word); $words{$name} = $word; } close(WORDSLIST); }

Adv. UNIX:Perl/833 wordslist Format fred camel barney llama betty oyster wilma oyster The code treats the file as four pairs: name secret-word

Adv. UNIX:Perl/834 Called in final1.pl: #!/usr/bin/perl &init_words; print "What is your name? "; $name = ; chop($name);...

Adv. UNIX:Perl/ File Tests sub init_words { # second version open(WORDSLIST, "wordslist"); if (-M WORDSLIST > 7) { die "Sorry, wordslist is too old"; } while ($name = ) { chop($name); $word = ; chop($word); $words{$name} = $word; } close(WORDSLIST); } -M is the file's modification date

Adv. UNIX:Perl/ The open() Command  Similar to popen() in C –the command argument is executed and can be written to via an output stream  In good_word :... open(MAIL, "| mail print MAIL "bad news $somename guessed $someguess\n"; close(MAIL);... mail MAIL

Adv. UNIX:Perl/ Filename Expansion v Assume several files of secret words: –ad.secret, yuk.secret  Modify init_words() to read in all of these –but only if the files are less than 7 days old  Store in the %words associative array Also called filename globbing

Adv. UNIX:Perl/838 sub init_words { # third version while ($filename = ) { open(WORDSLIST, $filename); if (-M WORDSLIST ) { chop($name); $word = ; chop($word); $words($name) = $word; } } close(WORDSLIST); } } filename expansion

Adv. UNIX:Perl/ The Password File v A typical password line: ad:x:42497:100:Dr.Andrew DAVISON,,,: /home/ad:/bin/bash –the user's details are in the 5th field u the GECOS field  $< always contains the user's ID number (UID)

Adv. UNIX:Perl/840 #!/usr/bin/perl # final1.pl = getpwuid( $< ); # get password data using the UID $name = $password[6]; # get the GECOS field (6th in Perl!) $name =~ s/,.*//; # throw away everything # after 1st comma if ($name =~ /^randal\b/i) { print "Hello, Sir Randal!\n"; }... There is a getpwuid() in C which does the same thing

Adv. UNIX:Perl/ Reporting  secret.pl : –list the *.secret files in the format: filename user-name secret-word

Adv. UNIX:Perl/842 secret.pl #!/usr/bin/perl while ($filename = ) { open(WORDSLIST, $filename); if (-M WORDSLIST ) { chop($name); $word = ; chop($word); write; # invoke STDOUT format } } close(WORDSLIST); } continued

Adv. UNIX:Perl/843 STDOUT Format Definition format @<<<<<<<<<<< $filename, $name, $word. field definition line field value line continued

Adv. UNIX:Perl/844 Top of Page Format v Used every 60 lines by default: format STDOUT_TOP = # field definition line $% # number of pages printed Filename Name Word =========== ======= ========.

Adv. UNIX:Perl/845 Output $ secret.pl Page 1 Filename Name Word ============= ======= ======== ad.secret andrew f1 ad.secret paul f2 ad.secret dr foobar yuk.secret jim c1 yuk.secret bob c2 $ The *.secret files may need to be 'touched'.

Adv. UNIX:Perl/ Using the UNIX DBM Database  In final1.pl, the time of the most recent correct guess is stored in %last_good $last_good{$name} = time;  Problem: %last_good will be lost when the script terminates.  Solution: store %last_good in a DBM database.

Adv. UNIX:Perl/ dbmopen(%last_good, "lastdb", 0666); $last_good{$name} = time; dbmclose(%last_good);... returns time in seconds since 1/1/1970 rw for everyone Revised final1.pl

Adv. UNIX:Perl/848 Using final1.pl v $ final1.pl Hello, Dr.Andrew DAVISON! What is the secret word? bingo Wrong, try again. What is the secret word? foobar $ foobar is the secret word for dr (see slide 45)

Adv. UNIX:Perl/849 List the Last Guessses (ex_last.pl) #!/usr/bin/perl dbmopen(%last_good,"lastdb",0666); foreach $name (sort keys(%last_good)) { $when = $last_good{$name}; $hours = (time - $when) / 3600; # compute hours ago write; # use STDOUT format } format STDOUT = last correct guess hours ago. $name, $hours.

Adv. UNIX:Perl/850 Output $ ex_last.pl User Andrew DAVIS: last correct guess was 2066 hours ago. User Dr.Andrew DA: last correct guess was 0.07 hours ago. $ last year, when my user details were different

Adv. UNIX:Perl/ The Web and Perl v Perl supports sockets for building Web clients and servers. v A easier and faster way is to use the LWP modules –designed for Web (client) tasks –hides low-level networking issues

Adv. UNIX:Perl/852 Main LWP Features v Object oriented notation v Supports all of the HTTP protocol –e.g. GET, POST, HEAD, redirection v Handles authentication v Deals with proxy servers v Can use timed action v Has a framework for writing Web 'robots'

Adv. UNIX:Perl/ Retrieve a Web Page v !/usr/bin/perl # geturl.pl use LWP::Simple; # use module LWP/Simple.pm print ( get $ARGV[0] ); $ geturl.pl Andrew Davison's Home Page at PSU :

Adv. UNIX:Perl/ Parse a Web Page v #!/usr/bin/perl # showurl.pl use LWP::Simple; use HTML::Parse; print parse_html( get $ARGV[0] )->format; $ showurl.pl Can't locate HTML/Parse.pm in... $ call format method on the result

Adv. UNIX:Perl/ Extract Links v #!/usr/bin/perl # showlinks.pl use LWP::Simple; use HTML::Parse; use HTML::Element; $phtml = parse_html( get $ARGV[0] ); for $phtml->extract_links() }) { $link = $_->[0]; # access array print "$link\n"; } $ showlinks.pl call extract_links method on the $phtml object

Adv. UNIX:Perl/ Deal with Proxies v #!/usr/bin/perl # hcat_proxy.pl use LWP::UserAgent; use use my $ua = new LWP::UserAgent; # local object $ua->proxy('http', ' $ua->no_proxy('coe.p-net'); my $request = new $ARGV[0]); my $response = $ua->request($request); if ($response->is_success) { print $response->content; } else { print $response->error_as_HTML; }

Adv. UNIX:Perl/857 Use (on fivedots) v $ perl hcat_proxy.pl Beginners Intro to Perl - Part Beginners Intro to Perl - Part 3 <meta name="robots" :

Adv. UNIX:Perl/ More Information on LWP  On calvin : –man LWP –pod2text < /usr/lib/perl5/lwpcook.pod v Perl modules (including LWP) are in: /usr/lib/perl5 /usr/lib/perl5 v Related modules: –HTML, HTTP, MIME, URI, WWW continued

Adv. UNIX:Perl/859 v Web Client Programming with Perl Clinton Wong O'Reilly, 1997 I have a copy