2.16k likes | 2.18k Views
Perl. P ractical E xtraction and R eport L anguage Not designed for the Web Designed by Larry Wall in 1986 to create reports Drew upon useful features in other programming languages ( P athologically E clectic R ubbish L ister ). Perl overview.
E N D
Perl • Practical Extraction and Report Language • Not designed for the Web • Designed by Larry Wall in 1986 to create reports • Drew upon useful features in other programming languages • (Pathologically Eclectic Rubbish Lister) UNIX System Programming
Perl overview • Originally called PEARL, but a conflict with an existing graphics language resulted in the shortening of the name • Language includes pattern matching, file handling, and scalar data • It has syntax patterned after C and was originally designed to operate as a shell script • Its power is that it views programs and files as data • It has proven to be an effective language for interacting with Web pages UNIX System Programming
Perl structure ► Variables in Perl are either integers or strings and begin with the symbol $. ► A simple Perl program consists of a series of print statements. ► It has the usual sequence of control structures such as for, while, and until loops and if conditional. UNIX System Programming
Perl is good for … • Quick scripts, complex scripts • Parsing & restructuring data files • CGI-BIN scripts • High-level programming • Networking libraries • Graphics libraries • Database interface libraries UNIX System Programming
Bad for ….. • Compute-intensive applications (use C, C++, Java) • Hardware interfacing (device drivers…) UNIX System Programming
Perl structure • Comment lines begin with: # • First line should look like: #!/bin/perl • File Naming Scheme • filename.pl (programs) • filename.pm (modules) • filename.ph (old Perl 4 header file) • Example prog: print “Hello, World!\n”; UNIX System Programming
Perl structure • Statements must end with semicolon. • $a = 0; • Should call exit() function when finished. • Exit value of zero means success • exit (0); # successful • Exit value non-zero means failure • exit (2); # failure UNIX System Programming
Perl structure ► Perl shares an ability to process regular expressions like several other process languages Example use: $ENV{'USER'} = ‘mvz’ will be true if login name mvz is the string $ENV{'USER'} (i.e., is the user running this program). This shows how Perl can interact with the system environment UNIX System Programming
Perl: Example script if ($food eq "spinach") { print "You ate spinach, so you get dessert!"; } elsif ($food eq "broccoli") { print "Broccoli's OK. Maybe you'll get dessert."; } else { print "No spinach, no dessert!"; } UNIX System Programming
Perl: The learning process • Access to Perl Interpreter on a server • Can download and install for free • Perl on UNIX server (needed to learn basic UNIX commands). • Basic Text Editor (e.g., Vi, Vim, Emacs, etc.) UNIX System Programming
Perl UNIX System Programming
Perl UNIX System Programming
Perl UNIX System Programming
Data Types • Integer • 25 750000 1000000000 • Nondecimal Integer • 0567 (Octal 567) • 0xff (Hex FF) • 0b10111011 (Binary 10111011) UNIX System Programming
Data Types • Perl allows underscores for readability: • 0b1011_1011 • 0x0000_FFFF UNIX System Programming
Data Types • Floating Point • 1.25 50.0 6.02e23 -1.6E-8 • String • ‘hi there’ “hi there, $name” qq(tin can) • print “Text Utility, version $ver\n”; UNIX System Programming
Perl UNIX System Programming
Perl strict - Perl pragma to restrict unsafe constructs use ‘refs’; // generate run-time errors if symbolic refs used use ‘vars’; // generate compile-time errors if var is not declared or out of scope use ‘subs’ // if bareword is used to call subs e.g., $SIG{PIPE} = Plumber; instead of $SIG{PIPE} = "Plumber” use strict; no strict ‘vars’ ; UNIX System Programming
Data Types • Boolean • 0 0.0 “” represents False • all other values represents True UNIX System Programming
Data Types • Scalar • $num = 14; • $fullname = “Cass A. Nova”; • Variable Names are case-sensitive • Underlines Allowed: $Program_Version = 1.0; UNIX System Programming
Perl UNIX System Programming
Perl UNIX System Programming
Perl UNIX System Programming
Perl UNIX System Programming
Basic I/O – Input from STDIN Evaluating this operator in a scalar context gives you the next line of input, or undef, if there are no more lines. $a = <STDIN>;# read the next line UNIX System Programming
Basic I/O – Input from STDIN ► Evaluating this operator in an array context gives you all of the remaining lines as a list. ► One line per element. @a = <STDIN>;# read the next line UNIX System Programming
Basic I/O – Input from STDIN ► To read a scalar value for <STDIN> and use value as the controlling expression of a loop: while (<STDIN>) {# like while ($_ = <STDIN>) chomp;# like chomp ($_ ) # process $_ here ; } UNIX System Programming
Input from Diamond Operator <> Unlike <STDIN>, < > gets data from file(s) specified on the command line that invoked the Perl program. E.g., if Perl file is called foo, consisting of #!/usr/bin/perl -w while (<>) { print $_ ; } UNIX System Programming
Input from Diamond Operator <> And you invoke foo with: foo file1 file2 file3 < > will read each line of file1 followed by each line of file2 followed by each line of file3. Acts like UNIX’s cat(enate) command UNIX System Programming
Input from Diamond Operator <> ►< > does not look at command line arguments. ► Uses the @ARGV array ►$#ARGV returns the number of arguments ► Set by Perl to contain the list of command-line arguments Example: set @ARGV in-program. @ARGV = (“passwd1”,”passwd2”,”passwd3”); while (<>) { #process files passwd? print “This line is $_ “; } UNIX System Programming
<> example: ►print lines that are not _________ ? while (<>) { chop; if ($_ ne “zatoichi”) { print “$_ \n“; } UNIX System Programming
Output to STDOUT ► print or printf: ► Parenthes is optional, needed for clarification & readability. E.g., print (2+3),”hello”; # wrong! Prints 5, ignores “hello” print ((2+3),”hello”); # right, prints 5hello print 2+3,”hello”; # also right, prints 5hello UNIX System Programming
Output to STDOUT ► printf for formatted output (from C) E.g., format width printf “%15s %5d %10.2f\n”, $s, $n, $r; string integer floating point UNIX System Programming
Built-in Perl Operators: chop • Scalar Context • Chop off and return the last character of a string $s = “string”; $c = chop($s); $s “strin” $c “g” • Array Context • Chop off the last character of every string in the array, but return the last character of the last element of the array. @s = (“s1”, “s2”, “s3”); chop(@s) @s = (“s”, “s”, “s”) UNIX System Programming
chomp • Scalar Context • Remove and return the last character of a string, if and only if it equals the current record separator value (\n). $s = “string\n”; $c = chomp($s); $s “string” $c “\n” • Array Context • Remove the last character of every string in an array only if it is the current record separator value. @s = (“hello\n”, “world”); chomp(@s) @s = (“hello”, “world”) UNIX System Programming
Perl UNIX System Programming
Perl UNIX System Programming
Perl UNIX System Programming
Examples with strings….. $fred = ‘hi’ ; $barney = “a test of ”.’$fred’; # yields ‘a test of $fred’ $barney2 = “a test of \$fred”; # same result as above UNIX System Programming
Examples with strings….. $fred = “pay”; $fredday = “wrong!”; $barney = “It’s $fredday” # not It’s payday, but It’s wrong! $barney = “It’s ${fred}day” # now, $barney = “It’s payday” $barney2 = “It’s $fred” . “day” # another way to do it, and another … $barney3 = “It’s”.$fred.”day”; UNIX System Programming
Arrays • List (one-dimensional array) @memory = (16, 32, 48, 64); @people = (“Alice”, “Alex”, “Albert”); • First element numbered 0 (can be changed) • Single elements are scalar: $names[0] = “Fred”; • Slices are ranges of elements @guys = @people[1..3]; • How big is my list? print “Number of people: $#people\n”; UNIX System Programming
Examples of Arrays (1, 2, 3) # array of three values (“fred”,4.5) # two values Elements can be expressions: ($a, 17) # two values, current value # of $a, and 17 ($b+$c, $a+$d) # two values Empty array: ( ) UNIX System Programming
Examples of Arrays Ranges allowed: (1..3) # same as (1, 2, 3) (2..4,10,12) # (2,3,4,10,12) ($a..$b) # depends on those values Float ranges: (1.2..5.2) # (1.2,2.2,3.2,4.2,5.2) (1.2..6.1) # (1.2,2.2,3.2,4.2,5.2) UNIX System Programming
Examples of Array Variables @fred = (1,2,3) # fred array gets 3 elements @barney = @fred # that is copied to $barney Array variable name may appear in array literal list: @fred = (“one”,”two”); @barney = (4,5,@fred,6,7); # = (4,5,”one”,”two”,6,7) @barney = (8, @barney); # puts 8 in front # of @barney UNIX System Programming
Examples of Array Variables When array variable is assigned a scalar variable, number assigned is length of array: @fred = (4,5,6); #initialize @fred $a = @fred; # $a gets 3, current length # of @fred UNIX System Programming
Examples – Element Access @fred = (7,8,9); $b = $fred[0]; # $b = 7 $fred[0] = 5 # @fred = (5,8,9) $fred[2]++ ; # increment 3rd element of # @fred ($fred[0],$fred[1]) = ($fred[1],$fred[0]) # swap first two UNIX System Programming
Examples – Element Access Slice: access list of elements @fred[0,1] ; # same as ($fred[0],$fred[1]) @fred[0,1] = @fred[1,0] # swap @fred[0,1,2] = @fred[1,1,1] # make all 3 elements same as # 2nd element @fred[1,2] =(9,10) # change last 2 values # 9 and 10 Note: @ instead of $ UNIX System Programming
Examples: Index Expressions Index can be any expression that returns a number, e.g., @fred = (7,8,9); $a = 2; $b = $fred[$a]; # $fred[2] = 9 $c = $fred[$a-2] # c = $fred[0] = 7 UNIX System Programming
Examples: Out-of-bounds access undef: value that represents something that is not defined. @fred = (1,2,3) $fred[i] for 0 > i > 2 yields undef value e.g., $barney = $fred[7] # $barney is now undef UNIX System Programming
Examples: Out-of-bounds assignment Assigning a value beyond the end of the current array automatically extends the array, giving undef to all intermediate values, if any. @fred = (1,2,3); $fred[3] = “hi”; # @fred is now (1,2,3,”hi”) $fred[6] = “ho”; # @fred = (1,2,3,”hi”,undef,undef,”ho”)) UNIX System Programming