319
 Perl Practical Extraction and Report Language (Larry Wall   1986) Manish Sharma [email protected] | D- 4 Sector 59. NOIDA 201307. India | | Main: +91 120 4074000 | Fax: +91 120 9999999 |

Complete Perl Tutorial

Embed Size (px)

Citation preview

Page 1: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 1/319

 

PerlPractical Extraction and Report Language

(Larry Wall  – 1986)

Manish Sharma

[email protected]

| D- 4 Sector 59. NOIDA 201307. India |

| Main: +91 120 4074000 | Fax: +91 120 9999999 |

Page 2: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 2/319

Introduction to Perl

“Practical Extraction and Report Language” 

Page 3: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 3/319

How to run Perl• Perl is an interpreted language. This means

you run it through an interpreter, not a compiler.• 2 methods:

 – Run interpreter directly, giving name of perlscript as

argument•  /usr/bin/perl myfile.pl

 – Run as a Unix shell program. First line of programwill tell the shell where the Perl interpreter is located

• This line is called the “shebang” • The shebang MUST be the very first line in the code

#!/usr/bin/perl

Page 4: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 4/319

One more step… • If you choose to use the shebang, you must

tell the OS that this is an executable file.

• Use chmod (see intro to unix slides)

• Usually only need to give yourself executepermissions.

• Once it‟s executable, type the filename at aprompt, and it runs.

• This is the preferred method of running Perl

Page 5: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 5/319

Perl Script Structure• semicolon ends each simple statement

• semicolon optional at final line of a block or loop – optional, but very recommended

• Functions & variables are case sensitive• Comments begin with # and extend to end of

line – don‟t try to use // or /* … */ 

• Perl will try to figure out what you mean

 – won‟t even give warnings, unless you tell it to  – either use warnings; or put – w after shebang or

command line – this is VERY Recommended.

Page 6: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 6/319

Variable Declarations

• In Perl, you do not need to declare yourvariables.

 – Unless you declare that you need to declare them

• To force needed declarations:– use strict;

– use warnings;

Page 7: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 7/319

Variables

• Three (basic) types of variables.

 – Scalar

 – Array

 – Hash

• There are others, but we‟ll talk about themat a later time…. 

Page 8: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 8/319

Scalars

• Scalar meaning “single value” 

• In C/C++, many many different kinds of

scalars: – int, float, double, char, bool

• In Perl, none of these types need to be

declared

• Scalar variable can hold all these types,and more.

Page 9: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 9/319

Scalars

• All scalar variables begin with a $

• next character is a letter or _ 

• remaining characters: letters, numbers, or _ • Variable names can be between 1 and 251

characters in length

• Ex: $foo, $a, $zebra1, $F87dr_df3• Wrong: $24da, $hi&bye, $bar$foo

Page 10: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 10/319

Scalar Assignments

• Scalars hold any data type:

• $foo = 3;

• $foo = 4.43;• $foo = „Z‟; 

• $foo = “Hello, I‟m Paul.” 

Page 11: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 11/319

Lists• A list (aka “list literal”) is a sequence of scalar 

values, separated by commas and enclosed inparentheses.

• A list can hold any number or type of scalars: – (43, “Hello World”, 3.1415) 

• Lists provide a way of assigning several scalarsat once:– ($a, $b, $c) = (42, “Foo bar”, $size); 

 – $a42, $b“Foo bar”, $c$size• List can also be represented with ranges:

– ($a, $b, $c, $d, $e) = (1..4, 10);

– ($x, $y, $z) = (“a” .. “c”); 

Page 12: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 12/319

List assignments

• Both sides of the = do not necessarily needto have the same number of elements.

• ($a, $b, $c) = (5, 10, 15, 20);

 – $a5, $b10, $c15. (20 ignored)• ($a, $b, $c) = (5, 10);

 – $a5, $b10, $cundef 

• ($t1, $t2) = ($t2, $t1);– $temp = $t1; $t1 = $t2; $t2 = $temp;

Page 13: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 13/319

Arrays

• Arrays are variables that hold a list

 – (analogous to difference between scalarvariable and string literal)

• much more dynamic than C/C++

 – no declaration of size, type

 – can hold any kind of value, and multiplekinds of values

• All array variables start with the @character– @arr, @foo, @My_Array, @temp34

Page 14: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 14/319

Array assignments• @foo = (1, 2, 3, 4);

• @bar=(“my”,“name”,“is”,“Paul”); 

• @temp = (34, „z‟, “Hi!”, 43.12); 

• Arrays are 0-indexed, just as in C/C++• $let = $temp[1]; # $let is now „z‟ 

 – NOTE: This is a *single value*, hence the $

• $bar[2] = “was”;  – @bar now (“my”, “name”, “was”, “Paul”); 

Page 15: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 15/319

Lists of Arrays

• Arrays within LHS of list will „eat‟ remainingvalues on RHS:– ($foo, @bar, $baz)=(1, 2, 3, 4, 5, 6);

– $foo=1; @bar=(2, 3, 4, 5, 6);$baz=undef;

• Arrays within RHS „flatten‟ to a single array. 

– @a1 = (1, 2, 3); @a2 = (4, 5, 6);– @a3 = (@a1, @a2);

 – @a3 (1, 2, 3, 4, 5, 6)

Page 16: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 16/319

Array vs. Scalar

• $foo = 3;

• @foo = (43.3, 10, 8, 5.12, “a”); 

• $foo and @foo are *completely unrelated*

• In fact, $foo has nothing to do with $foo[2];

• “This may seem a bit weird, but that‟s okay,

because itis 

 weird.”  – Programming Perl, pg. 54

Page 17: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 17/319

More about arrays• special variable for each array:

– @foo = (6, 25, 43, 31); – $#foo 3. Last index of @foo.

 – $foo[$#foo] 31;

• This can be used to dynamically alter the sizeof an array:– $#foo = 5; 

• creates two undefined values on the end of @foo– $#foo = 2; 

• destroys all but the first three elements of @foo

Page 18: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 18/319

Even more about arrays

• Arrays can take a negative index as well.(since 0 is first, -1 is last, -2 is second-to-last,etc)

– $foo[$#foo] and $foo[-1] always refer tosame element

• “Slices” – piece of an array (or list) (or hash)

– @bar = @foo[1..3];  @bar

(25, 43, 31)– @bar = @foo[0,2];  @bar(3, 43)

– @bar = @foo[1];  @bar(25);

• You probably don‟t want that 

Page 19: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 19/319

Join/Split

• Built-in Perl functions

• split: split a string into a list of values

– $BigString = “Hello,_I_am_Paul”; – @strings = split „_‟, $BigString; 

 – @strings (“Hello,”, “I”, “am”, “Paul”); 

•  join: join a list/array of values together– $BigString = join „ ‟, @strings; 

 – $BigString “Hello, I am Paul”; 

Page 20: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 20/319

Hash• (somewhat) Analogous to hashtable datatype.

 – More closely resembles STL map• aka “Associative Array” – ie, array not indexed by

numerical sequence.

• list of keys and values.

 – Keys and Values can be any kind of scalar value, includingmixed values within the same hash

• All hash variables start with %

• Use to keep list of corresponding values – TIP: Any time you feel the need to have two separate arrays,

and do something with elements at corresponding positionsin the arrays (but don‟t care where in array elements actually

are), USE A HASH

Page 21: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 21/319

Hash example• Want a list of short names for months:

%months = (

“Jan” => “January”, 

“Feb” => “February”, 

“Mar” => “March”, 

… 

);• reference by *curly* brackets… 

 – Avoid confusion with array notation

• $month{“Jan”}   “January”; 

Page 22: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 22/319

More Hash Examples

• Hash elements can be dynamically created (in fact, socan entire hashes)

• $profs{“Perl”} = “Paul Lalli”; 

• $profs{“Op Sys”} = “Robert Ingalls”; 

• $profs{“CS1”} = “David Spooner”; • %profs (“Perl” => “Paul Lalli”,

•   “Op Sys” => “Robert Ingalls”,

•   “CS1” => “David Spooner”); 

• Hashes will “flatten” into normal lists: 

• @p_arr = %profs;

• @p_arr(“Perl”, “Paul Lalli”, “Op Sys”, “Robert

Ingalls”, “CS1”, “David Spooner”) 

Page 23: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 23/319

Special Variables• See Chapter 2 of Camel for full list

• $!  – last error received by operating system

• $,  – string used to separate items in a printed list 

• $_ - “default” variable, used by several functions 

• %ENV   – Environment variables

• @INC  – directories Perl looks for include files

• $0  – name of currently running script

• @ARGV   – command line arguments

• $#ARGV   – # of command line arguments

Page 24: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 24/319

Very basic I/O

• simple introduction to reading/writing fromkeyboard/terminal.

• This will be just enough to allow us to do

some examples, if necessary.

Page 25: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 25/319

Output to terminal

• the print statement.

• Takes a list of arguments to print out

• Before the list of arguments, optionallyspecify a filehandle to which to print

 – If omitted, default to STDOUT

 – Also have STDIN, STDERR

• If the list of arguments is omitted, printwhatever value is currently in variable $_ 

Page 26: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 26/319

Output examples• Hello World program:

#!/usr/bin/env perl

 print “Hello World \n”; 

• as this is Perl, you can put string in

parentheses, but you don‟t need to (usually – because this is Perl).

• more examples:– print “My name is $name\n”; 

– print “Hi ”, “what‟s ”, “yours?\n”; 

– print 5 + 3;

– print ((4 * 4). “\n”);

O t h

Page 27: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 27/319

One catch• Recall that print takes a list of arguments.

• By default, print outputs that list to theterminal one right after another@nums = (23, 42, 68);

 print @nums, “\n”; 

• 234268

• To change string printed between list items,set the $, variable:

$, = “, ”;  print @nums, “\n”; 

• 23, 42, 68

Page 28: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 28/319

Input from keyboard

• read line operator: <>

 – aka “angle operator”, “diamond operator” 

 – Encloses file handle to read from. Defaults toSTDIN, which is what we want.

• $input = <>; – read one line from STDIN, and save in $input

• @input = <>;

 – read all lines from STDIN, and save as array in@input

Page 29: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 29/319

Our First Bit of Magic• The Camel will describe several Perl features as

“magical”. • The <> operator is the first such feature.

• If you pass the name of a file (or files) as command linearguments to your script, <> does not read from STDIN.

• Instead, it will automatically open the first file on thecommand line, and read from that file.

• When first file exhausted, it opens and reads from nextfile.

• When all files exhausted, THEN <> reads from STDIN

• If you want to read from STDIN before files have beenread, must do it explicitly:

– $line = <STDIN>;

Page 30: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 30/319

Chop & Chomp• When reading in a line, newline (“ \ n”) is included. 

 – Usually don‟t want that.• chomp will remove the newline from the end of a string

• chop takes off last character of a string, regardless of

what it is.

 – Hence, chomp is “safer”. 

• chomp ($foo = <>);

 – Very common method of reading in one string from input.

• chomp actually takes a list, and will chomp eachelement of that list

• chomp (@s = (“foo\n”,“bar\n”,“baz\n”)); 

• @s

 (“foo”, “bar”, “baz”); 

Page 31: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 31/319

Control Structures

Page 32: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 32/319

if-elsif-else• semantically the same as C/C++

• syntactically, slightly different.if ($a > 0){

 print “\$a is positive\n”; 

} elsif ($a == 0){ print “\$a equals 0\n”; 

} else {

 print “\$a is negative\n”; }

• brackets are *required*!

Page 33: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 33/319

unless

• another way of writing if (!…) {…} 

• analogous to English meaning of “unless” 

•unless (CONDITION) BLOCK – “do BLOCK unless CONDITION is true” 

 – “do BLOCK if CONDITION is false” 

• can use elsif and else with unless aswell

Page 34: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 34/319

while/until loops

• while is similar to C/C++• while (EXPR) BLOCK

 – “While EXPR is true, do BLOCK” 

• until (EXPR) BLOCK – “Until EXPR is true, do BLOCK” 

 – “While EXPR is false, do BLOCK” 

 – another way of saying while (!…) {…} 

• again, brackets are *required*

Page 35: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 35/319

do• Execute all statements in following block,

and return value of last statement executed• When modified by while or until, run

through block once before checkingcondition

do {

$i++;

} while ($i < 10);

• Note that Perl does not consider do to bean actual loop structure. This is importantlater on… 

Page 36: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 36/319

for loops

• Perl has 2 styles of for.

• First kind is virtually identical to C/C++

• for (INIT; TEST; INCREMENT) { }for ($i = 0; $i < 10; $i++){ print “\$i = $i\n”;

}• yes, the brackets are required.

Page 37: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 37/319

foreach loops

• Second kind of for loop in Perl – no equivalent in core C/C++ language

• foreach VAR (LIST) {}

• each member of LIST is assigned to VAR, andthe loop executed

$sum = 0;

foreach $value (@nums){

$sum += $value;

}

More About for/foreach

Page 38: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 38/319

More About for/foreach

• for and foreach are actually synonyms

 – Anywhere you see “for” you can replace it with“foreach” and viceversa 

• Without changing ANYTHING ELSE

 – they can be used interchangeably.

 – usually easier to read if conventions followed:•for ($i = 0; $i<10; $i++) {}

•foreach $item (@array) {}

 – but this is just as syntactically valid:•foreach ($i = 0; $i<10; $i++) {}

•for $i (@array) {}

Page 39: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 39/319

Two More Things… (about for) 

• foreach VAR (LIST) {}

• while iterating through list, VAR becomes an*alias* to each member of LIST

 – Changes within loop to VAR affect LIST• if VAR omitted, $_ used

@array = (1, 2, 3, 4, 5);

foreach (@array) {$_ *= 2;

}

• @array now (2, 4, 6, 8, 10)

Reading it in English

Page 40: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 40/319

Reading it in English

• Perl has a cute little feature that makes simple

loop constructs more readable• If your if, unless, while, until, orforeach block contains only a singlestatement, you can put the condition at the end

of the statement:• if ($a > 10) {print “\$a is $a\n”;} 

• print “\$a is $a\n” if $a > 10; 

• Using this modifier method, brackets andparentheses are unneeded

• This is syntactic sugar – whichever looks and

feels right to you is the way to go.

Page 41: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 41/319

Loop Control – next, last, redo

• last  equivalent of C++ break – exit innermost loop

• next  (mostly) equivalent of C++ continue

 – begin next iteration of innermost loop• redo  no real equivalent in C++

 – restart the current loop, without evaluatingconditional

• Recall that do is not a looping block. Hence,you cannot use these keywords in a do block(even if it‟s modified by while) 

Page 42: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 42/319

continue block• while, until, and foreach loops can have a

continue block.• placed after end of loop, executed at end of eachiteration

• executed even if the loop is broken out of via next 

(but not if broken via last or redo)foreach $i (@array){

next if ($i % 2 != 0);

$sum += $i;

} continue {

$nums++;

}

Page 43: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 43/319

Breaking Out of More Loops• next, last, redo operate on innermost loop

• Labels are needed to break out of nesting loopsTOP: while ($i < 10){ MIDDLE: while ($j > 20) {

BOTTOM: foreach (@array){

if ($j % 2 != 0){next MIDDLE;}if ($i * 3 < 10){

last TOP;}}

}

}

Page 44: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 44/319

goto

• yes, it exists and works as in any otherlanguage

• LABEL:

… some code … 

goto LABEL;

Page 45: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 45/319

Interpolation

Variable Interpolation,

Backslash Interpolation

Page 46: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 46/319

Interpolation

• Sometimes called “substitution”  – In Perl, “Substitution” means something else 

• Interpolation = replacing symbol/variable

with its meaning/value within a string• Two kinds of interpolation – variable and

backslash

• Done *only* in double-quoted strings, notsingle-quoted strings.

Page 47: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 47/319

Backslash interpolation

• aka: character interpolation, characterescapes, escape sequences.

• When any of these sequences are foundinside a double – quoted string, they‟reinterpolated

• All escapes listed on page 61 of Camel

• Most common: “\n”, “\t” 

Page 48: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 48/319

Backslashes in Reverse

• A backslash in a double-quoted string makesnormal characters special.

 – makes „n‟ into a newline, „t‟ into tab, etc 

• Also makes special characters normal. – $, @, %, \ are all special. If you want to use themin a double quoted string, must backslash them.

– print “My address is [email protected]” 

• Error, thinks @rpi is an array

– print “My address is bauerd \@rpi.edu” 

• Prints correctly.

Page 49: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 49/319

Translation Escapes

• pg 61, table 2-2 of Camel

• \u  – next character is uppercase

•\l

  – next character is lowercase

• \U  – all characters until \E are uppercase

• \L  – all characters until \E are lowercase

• \Q  – all characters until \E are backslashed• \E  – end \U, \L, or \Q

Page 50: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 50/319

Variable Interpolation

• variables found within “ ” are interpolated.• „ ‟ strings are NOT searched for interpolation• $foo = “hello”; 

• $bar = “$foo world”;  – $bar gets value: “hello world” 

• $bar2 = „$foo world‟; 

 – $bar2 gets value: „$foo world‟ 

D ‟t f th

Page 51: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 51/319

Don‟t confuse the parser  • perl looks in double-quoted strings for anything

that looks like a variable.• The parser stops only when it gets to a

character that cannot be part of the variable

name$thing = “bucket”; 

 print “I have two $things\n”; 

• perl assumes you are printing a variable $things• Specify where the variable ends with {}

 print “I have two ${thing}s\n”; 

Wh b i l d?

Page 52: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 52/319

What can be interpolated?• Scalars, arrays, slices of arrays, slices of

hash – NOT entire hashes

• Arrays (and slices) will print out each

member of array separated by a space:– @array = (1, 3, 5, 7);

– print “The numbers are @array.\n”; 

 – output: The numbers are 1 3 5 7.• Change separation sequence via $” variable

Quote-like operators

Page 53: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 53/319

Quote like operators

• You might not always want to specify a stringby double quotes:– “He said, “John said, “blah””\n”. 

 – You would have to backslash all those quotes

• Perl allows you to choose your own quoting

delimiters, via the quote-like operators: q() and qq()

• A string in a q() block is treated as a single-

quoted string.• A string in a qq() block is treated as a

double-quoted string.

Page 54: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 54/319

Choosing your own delimiter

• Choose any non-alpha-numeric character: /, !• print qq/Hi John\n/;

• $s = q!Foo Bar!;

• If you choose a paren-like character – (), [],{}, you must start the string with the left

character and end it with the right.

• print “I said \“Jon said \“take it\”\”\n”; 

• Is equivalent to:• print qq(I said “Jon said “take it””\n);

Page 55: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 55/319

Operators

Page 56: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 56/319

Operators

• Perl has MANY operators.

• Many operators have numeric and stringversion

 – remember Perl will convert variable type foryou.

• We will go through them in decreasing

precedence.

Page 57: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 57/319

Increment/Decrement

• ++ and --  – Prefix and Postfix work as they do in C/C++

– $y = 5; $x = $y++;

• $y 6, $x 5– $y = 5; $x = ++$y;

• $y 6; $x 6

Page 58: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 58/319

Incrementation Magic

• ++ is “magical”. (-- is not) – if value is purely numeric, works as expected

 – if string value, or ever used as string, magichappens

 – „99‟++ „100‟ 

 – „a9‟++ „b0‟ 

 – „Az‟++ „Ba‟ 

 – „zz‟++ „aaa‟ 

• Try it, see what happens.

Page 59: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 59/319

Even better… 

• In addition to that magic, ++ will alsoautomatically convert undef to numeric

context, and then increment it.

#!/usr/bin/env perl – w

$a++;

 print “$a\n”; 

• Prints “1” with no errors/warnings 

• undef is equivalent to 0 in numeric context

E ti ti

Page 60: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 60/319

Exponentiation

• ** Exponentiation. – works on floating points or integers

– 2**3  pow(2, 3) “2 to the power of 3” 8

• NOTE: higher precedence than negation – -2**4 -(2**4) -16

Page 61: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 61/319

Unary Operators

• ! – logical negation– 0, “0”, “”, (), undef  all false

 – anything else true

• - – arithmetic negation (if numeric) – if non-numeric, „negates‟ the string 

 – ex: $foo = “-abc”; $bar = -$foo; 

 – $bar gets value “+abc”; • ~ – bitwise negation

Page 62: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 62/319

Multiplicative

•  / -- Division. Done in floating point.

• % -- Modulus. Same as in C.

• * -- Numeric multiplication

• x -- String multiplication (aka repetition).

 – 123 * 3 369

 – 123 x 3  „123123123‟ (scalar context) 

 – (123) x 3 (123, 123, 123) (list context)

Page 63: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 63/319

Additive

• + – normal addition

• - – normal subtraction

• . – string concatenation– $var1 = “hello”; $var2 = “world”; 

– $var3 = $var1 . $var2;• $var3 contains “helloworld” 

– $var3 = “$var1 $var2”; • $var3 contains “hello world” 

Page 64: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 64/319

Shift operators

• << and >> - work as in C.

 – Shift bits in left argument number of places inright argument

• 1 << 4  16 – 0000 00012 << 4 0000 10002  1610

• 32 >> 4  2

 – 0010 00002 >> 4 0000 00102  210

Page 65: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 65/319

Relational Operators

Numeric String Meaning

> gt Greater Than

>= ge Greater Than or Equal

 < lt Less Than

 <= le Less Than or Equal

Page 66: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 66/319

Equality Operators

Numeric String Meaning== eq  Equal to

!= ne not equal to

 <=> cmp comparison

•About the comparison operator:

• -1 if left < right

• 0 if left == right

1 if left > right

Page 67: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 67/319

The danger of mixing contexts

• $s1 = “Foo Bar”; • $s2 = “Hello World”; 

• if ($s1 == $s2){print “Yes\n”; } 

• $a = <>; #user enters 42

• $b = <>; #user enters 42.00

• if ($a eq $b) {print “Yes\n”; } 

Page 68: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 68/319

Bitwise Operators

• & -- AND. | -- OR ^ -- XOR – & has higher precedence

• if either value numeric:

 – convert to integer, – bitwise comparison on integers

• if both values strings:

 – bitwise comparison on corresponding bitsfrom the two strings

Page 69: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 69/319

Logical Operators

• && - AND || - OR – && has higher precedence

• operate in short-circuit evaluation

 – ie, evaluate only what‟s needed  – creates this common Perl line:

• open (FILE, “file.txt”) || 

die “Can‟t open file.txt”; • return last value evaluated

Page 70: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 70/319

Conditional Operator

• ?: -- Trinary operator in C.

• like an if-else statement, but it‟s anexpression– $a = $ok ? $b : $c;

 – if $ok is true, $a = $b. if $ok is false, $a = $c

Page 71: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 71/319

Assignment operators

• =, **=, *=, /=, %=, x=, +=, -=, .=,

• &=, |=, ^=, <<=, >>=, &&=, ||=

• In all cases, all assignments of form

• TARGET OP= EXPR 

• evaluate as:

• TARGET = TARGET OP EXPR 

C O

Page 72: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 72/319

Comma Operator

• Scalar context: – evaluate each list element, left to right.

Throw away all but last value.

– $a = (fctn(), fctn2(), fctn3());

• fctn() and fctn2() called, $a gets value of fctn3()

• Array context:

 – list separator, as in array assignment

– @a = (fctn(), fctn2(), fctn3());

• @a gets return values of ALL three functions

Page 73: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 73/319

Logical and, or, not, xor

• Functionally equivalent to &&, ||, !

• $xyz = $x || $y || $z;

• $xyz = $x or $y or $z;

• What‟s the difference? 

Page 74: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 74/319

Incomplete list

• some skipped over, we‟ll talk about themlater.

Page 75: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 75/319

Context

Page 76: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 76/319

Context

• Every operation in Perl is done in aspecific “context”. – mode, manner, meaning

• return value of operation can changedepending on its context

• Perl variables and functions are evaluatedin whatever context Perl is expecting forthat situation

• Two *major* contexts – Scalar & List

S C

Page 77: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 77/319

Scalar Context

• $x = fctn();

• if (fctn() < 5) { … } 

• Perl is “expecting” a scalar, so fctn() isevaluated in scalar context

 – assign to a scalar variable, or use an operatoror function that takes a scalar argument

• Also, force scalar context by scalar keyword– $x = scalar fctn();

Scalar Sub-contexts

Page 78: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 78/319

Scalar Sub contexts• Scalar values can be evaluated in Boolean,

String, or Numeric contexts• Boolean:

– 0, “0”, “”, and undef are all false

 – anything else is true

• String: „hello world‟, “I have 4” 

• Numeric: 5, 3.4, -5

• Perl will *automatically* convert to and fromeach of these contexts for you. Almost neverneed to concern yourself with them.

Automatic Conversions

Page 79: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 79/319

• If a number is used as a string, the conversion isstraight forward.– 853 becomes “853” 

– -4.7 becomes “-4.7” 

• If a string is used as a number, Perl will convert the

string based on the first character(s) – If first character is „numeric‟ (ie, number, period (decimal),or negative (hyphen)), converted number reads from startto first non-numeric character.

– “-534.4ab32” -534.4

 – If first character is non-numeric, converted number is 0.– “a4332.5” 0

• If a scalar is used in a conditional (if, while), it istreated as a boolean value

When does this happen?

Page 80: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 80/319

When does this happen?$foo = 4;

 print “Enter a number”; $bar = <STDIN>; #do we need to chomp?

$sum = $foo + $bar;

• Note that $bar is unaffected. It‟s used asa number in that one statement,assuming the input started with a numericvalue

• Method for checking input for numericdata involves Regular Expressions – don‟t worry about it now 

Li C

Page 81: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 81/319

List Context

• @x = fctn();

• @x = split (“ ”, fctn()); 

• Assign to a list/array, or use in a function oroperator that is expecting a list

• There is no analogy to the scalar keyword

for lists. If you use a scalar in any kind of

list context, it is “promoted” to a list. – @array = 5;

 – @array gets value: (5)

C t t F

Page 82: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 82/319

Context Fun• arrays evaluated in scalar context produce the

size of that array– @x = (4, 8, 12);– $sizex = @x; – $sizex is assigned value 3.

• print “@x has ” . @x . “ values.\n”;  – 4 8 12 has 3 values.

•  @x = (“a”, “b”, “c”); • $y = @x; # Scalar context

• ($z) = @x; # List context• $y 3, $z “a” 

d f

Page 83: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 83/319

undef

• Any Perl variable which exists but is notdefined has default value undef

– ($a,$b,$c)=(15,20); # $c == undef

• In string context, undef “” 

• In numeric context, undef 0

• In boolean context, undef false

• In list context, undef () 

 – ie, an empty list

Page 84: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 84/319

Command Line Arguments

C d Li A t

Page 85: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 85/319

Command Line Arguments

• Similar (yet different) to C/C++

• in C/C++:– argv[] contains program name and arguments

– argc contains number of arguments plus one

• in Perl:– @ARGV contains list of arguments

– $0 contains program name

Examples:

Page 86: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 86/319

Examples:

• myscript 15 4 hello– array @ARGV   (15, 4, “hello”) 

– scalar $0  “myscript” 

– scalar(@ARGV) 

3• myscript

– @ARGV   ( )

– $0 

 “myscript” – scalar(@ARGV)  0

Page 87: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 87/319

Built-In Functions

Page 88: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 88/319

h ARRAY LIST

Page 89: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 89/319

push ARRAY, LIST

• add values of LIST to end of ARRAY

• push @array, 5;

 – adds 5 to end of @array

• push @foo, (4, 3, 2);

 – adds 4, 3, and 2, to the end of @foo

• @a = (1, 2, 3); @b = (10, 11, 12);

• push @a, @b;

 – @a now (1, 2, 3, 10, 11, 12)

pop ARRAY

Page 90: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 90/319

pop ARRAY

• remove and return last element of ARRAY• @array = (1, 5, 10, 20);

• $last = pop @array;

 – $last 20 – @array (1, 5, 10)

• @empty = ();

• $value = pop @empty; – $value undef.

unshift ARRAY LIST

Page 91: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 91/319

unshift ARRAY, LIST

• Add elements of LIST to front of ARRAY

• unshift @array, 5;

 – adds 5 to front of @array

• unshift @foo, (4, 3, 2);

 – adds 4, 3, and 2, to the front of @foo

• @a = (1, 2, 3); @b = (10, 11, 12);

• unshift @a, @b;

 – @a now (10, 11, 12, 1, 2, 3)

shift ARRAY

Page 92: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 92/319

shift ARRAY• remove and return first element of ARRAY

• @array = (1, 5, 10, 20);• $first = shift @array;

 – $first 1

 – @array (5, 10, 20);• @empty = ();

• $value = shift @empty;

 – $value undef

splice ARRAY, OFFSET, LENGTH, LIST

Page 93: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 93/319

• functionality of push,  pop, shift, unshift – (plus a little bit more)

• remove LENGTH elements from ARRAY,starting at position OFFSET, and replace themwith LIST.

• In scalar context, return last element removed• In list context, return all elements removed

• @foo = (1 .. 10);

• @a = splice @foo, 4, 3, „a‟ .. „e‟; • @foo (1, 2, 3, 4, „a‟, „b‟, „c‟, „d‟, „e‟, 8, 9, 10) 

 – @a (5, 6, 7)

splice w/o some arguments

Page 94: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 94/319

splice w/o some arguments

• splice ARRAY, OFFSET, LENGTH, LIST

• Omit LIST: remove elements, don‟t replace 

• Omit LIST and LENGTH: remove allelements starting at OFFSET

• Omit LIST, LENGTH, and OFFSET: clearentire ARRAY as it‟s being read 

Page 95: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 95/319

keys HASH; values HASH

Page 96: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 96/319

• keys  return list of all keys from HASH

 – seemingly random order• values  return list of all values from HASH

 – same „random‟ order as keys produces 

•Example hash:– %months = („Jan‟ => „January‟, „Feb‟=> „February‟, „Mar‟ => „March‟, …); 

• keys (%months)  („Jan‟, „Feb‟, „Mar‟, …) 

• values (%months)  („January‟, „February‟,„March‟, …)  – NOT necessarily in that order.

length EXPR

Page 97: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 97/319

length EXPR

• return number of characters in EXPR• $a = “Hello\n”; 

• $b = length $a;

• $b 6

• Cannot use to find size of array or hash

index STR, SUBSTR, OFFSET

Page 98: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 98/319

index STR, SUBSTR, OFFSET

• Look for first occurrence of SUBSTR within

STR (starting at OFFSET) – OFFSET defaults to 0 if omitted

• Return first position within STR that SUBSTR is

found.– $a = index “Hello World \n”, “o”; 

– $b = index “Hello World \n”, “o”, $a+1; 

 – $a 4, $b 7

• Returns -1 if SUBSTR not found.

• rindex  return last position found

reverse LIST

Page 99: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 99/319

• in list context, return an array consisting of

elements in LIST, in opposite order– @foo = (1 .. 10);

– @bar = reverse @foo;

 – @foo

(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) – @bar (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)

• in scalar context, take LIST, concatenate all

elements into a string, and return reverse ofthat string– $rev = reverse @foo;

 – $rev “01987654321” 

stat FILEHANDLE

Page 100: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 100/319

• Return a 13-element list containing statisticsabout file named by FILEHANDLE – can also be used on a string containing a file name.

• ($dev, $ino, $mode, $nlink, $uid,$gid, $rdev, $size, $atime, $mtime,

$ctime, $blksize, $blocks) = stat$filename;

• See Camel page 801 for full description

• Common uses:– @info = stat $file

– print “File size is $info[7], lastaccess time is $info[8], last modified 

time is $info[9]\n”; 

sort LIST

Page 101: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 101/319

• returns LIST sorted in “ASCIIbetical” order.

– undef comes before “”, then sort by ASCII chart – does not affect LIST that is passed in

 – note that by ASCII chart, “100” comes before “99” 

• @f = (“Banana”, “Apple”, “Carrot”); 

• @sorted = sort @f;

• @sorted (“Apple”, “Banana”, “Carrot”)  – @f unmodified

• @nums = (97 .. 102);• @s_nums = sort @nums;

• @s_nums = (100, 101, 102, 97, 98, 99)

Advanced Sorting

Page 102: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 102/319

• You can tell sort how you want a function sorted – Write a small function describing the sort order

 – In this function, Perl will assign $a and $b to be twolist elements.

• If you want $a to come before $b in sort order,

return –1. If you want $b first, return 1. – if order of $a and $b doesn‟t matter, return 0 

sub numeric_sort{

if ($a < $b) {return –1;}elsif ($a > $b) {return 1;}

else {return 0;}

}

Using Your Own SortN th t h th t f ti it i t

Page 103: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 103/319

• Now that we have that function, use it in sort:– @nums = (4, 2, 9, 10, 14, 11);

– @sorted = sort numeric_sort @nums;

 – @sorted (2, 4, 9, 10, 11, 14);

• Look at that function again… 

if ($a < $b) {return –1;}

elsif ($a > $b) {return 1;}

else {return 0;}• This can be simplified quite a bit.

– return ($a <=> $b);

Simplifying Further

Page 104: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 104/319

Simplifying Further

• We now have:

sub by_number{

return ($a <=> $b);

}• When sort function is that simple, don‟t even

need to declare it:

• @sorted = sort {$a <=> $b} @nums;• Excellent description of sorting in Llama

chapter 15

Page 105: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 105/319

References

Page 106: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 106/319

• Analagous (somewhat) to pointers in C/C++

 – Far less messy, and definitely less dangerous• Assign the memory location of a variable to

a scalar variable.

• Use the \ to create a reference:• @foo = (1, 2, 3);

• $foo_ref = \@foo;

• $foo_ref now contains a reference to the

array @foo; – Changes to @foo will affect array referenced by

$foo_ref

De-Referencing

Page 107: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 107/319

• Once you have a reference, de-reference it

using the appropriate variable symbol (@ forarray, % for hash, etc)

• $foo_ref = \@foo;

• @new_array = @$foo_ref; – @new_array is a different array, which contains

the same values of members that the arrayreferenced by $foo_ref contained.

 – Changes to @foo (or even $foo_ref) do NOTaffect @new_array

Referencing Other Types

Page 108: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 108/319

• You can also reference other kinds ofvariables:

• %hash=(„Paul‟=>23, „Justin‟=>22); 

• $h_ref = \%hash;

• $bar = “hello world \n”; 

• $bar_ref = \$bar;

Anonymous References• A value need not be contained in a defined variable

Page 109: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 109/319

A value need not be contained in a defined variableto create a reference.

• To create an anonymous array reference: – use square brackets, instead of parens

• $a_ref = [20, 30, 50, “hi!!”]; 

• @a = @$a_ref; – @a (20, 30, 50, “hi!!”); 

• For hash references, use curly brackets, instead ofparens:

• $h_ref={“sky”=>„blue‟,“grass”=>„green‟} 

• %h = %$h_ref;

 – %h (“sky” => „blue‟, “grass” => „green‟); 

• To de-reference specific element of references

TMTOWTDI• In fact, there are three… 

Page 110: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 110/319

ac , e e a e ee

• $a_ref = [“Hi”, “Hiya”, “Hello”]; 

• $$a_ref[2] = “Hello”; • ${$a_ref}[2] = “Hello”; 

• $a_ref-> [2] = “Hello”; 

• $$h_ref{$key} = $value;

• ${$h_ref}{$key} = $value;

• $h_ref-> {$key} = $value;• These are all valid and acceptable. The form

you choose is whatever looks the best to

you

Dimensional Array

Page 111: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 111/319

• To create a two dimensional array, create anarray of array references:

• @two_d = ([1, 2], [3, 4], [5, 6]);

• $two_d[1] is a reference to an array containing(3, 4)

• @{$two_d[1]} is an array containing (3, 4)

• $two_d[1][0] is the scalar value 3.

More Complicated• Using similar methods, you can create arrays

Page 112: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 112/319

g , y yof hashes, hashes of arrays, hashes of

hashes, arrays of arrays of hashes, hashes ofhashes of arrays, arrays of hashes of arrays, .. . . .

%letters = (

„lower‟ => [„a‟ .. „z‟], 

„upper‟ => [„A‟ .. „Z‟] 

)

• $letters{„lower‟} is an array reference;

• @{$letters{„lower‟}} is an array; 

• $letters{„lower‟}[1] is scalar value „b‟. 

Page 113: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 113/319

Subroutines

Subroutines

Page 114: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 114/319

Subroutines

• aka: user-defined functions, methods,procedures, sub-procedures, etc etc etc

• We‟ll just say Subroutines. 

 – “Functions” generally means built-in functions

• We‟ll attempt to start out most basic, andwork our way up to complicated.

The Basicssub myfunc

Page 115: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 115/319

{

 print “Hey, I‟m in a function!\n”; 

}… 

 myfunc( ); # call to subroutine

• Because the subroutine is already declared, () areoptional (ie, you can just say myfunc; ) – If you call the function before declaring it, the () are required

• You can declare a subroutine without defining it (yet):–sub myfunc; – Make sure you define it eventually…. 

• actual name of the subroutine is &myfunc

 – ampersand not normally necessary to call it

Parameters• (aka Arguments, inputs, etc)

Page 116: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 116/319

(aka Arguments, inputs, etc)

• You can call any subroutine with any number

of parameters.• The parameters get passed in via local @_  

variable.

sub myfunc{foreach $word (@_){

 print “$word ”; 

}$foobar = 82;

 myfunc “hello”, “world”, $foobar; 

• prints “hello world 82”

Passing current parameters

Page 117: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 117/319

• Can call a function with the current value of

@_ as the parameter list by using &.• &myfunc;

– myfunc‟s @_ is alias to current @_ 

• same as saying myfunc(@_);

 – it‟s faster internally… 

Squashing array parameters

Page 118: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 118/319

q g y p

• If arrays or hashes are passed into asubroutine, they get „squashed‟ into one flatarray: @_ 

@a = (1, 2, 3);

@b = (8, 9, 10); myfunc (@a, @b);

• inside myfunc, @_  (1, 2, 3, 8, 9, 10);

• Maybe this is what you want. – if not, you need to use references… 

References in Parameters

Page 119: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 119/319

• To pass arrays (or hashes), and not squashthem:

sub myfunc{

($ref1, $ref2) = @_;

@x = @$ref1;@y = @$ref2;

… 

}@a = (1, 2, 3);

@b = (8, 9, 10);

myfunc (\@a \@b);

ass ng y re erenceWithin subroutine, changes to the array reference passed in

Page 120: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 120/319

sub f1{$ref1 = shift(@_);

$ref2 = shift(@_);

@a2 = @$ref2;

for ($i=0; $i<@$ref1; $i++){$$ref1[$i]++;

}

for ($i=0; $i<@a2; $i++){

$a2[$i]--;

}

}

, g y p

affect the array that was referenced:

@foo=(1, 1, 1);

@bar=(1, 1, 1);

f1(\@foo, \@bar);

At this point,

@foo (2, 2, 2), but

@bar (1, 1, 1)

Page 121: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 121/319

Return issues

Page 122: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 122/319

• Can return values in list or scalar context.

sub toupper{@params = @_;

foreach (@params) {tr/a-z/A-Z/;}

return @params;}

@uppers = toupper ($word1, $word2);

$upper = toupper($word1, $word2);

• $upper gets size of @params

Anonymous functions

Page 123: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 123/319

• You can declare a subroutine without givingit a name.

• Store the „return value‟ of sub in a scalar

variable– $subref = sub { print “Hello\n”; }; 

• to call, de-reference the stored value:– &$subref;

• works with parameters too..– &$subref($param1, $param2); 

Scoping

Page 124: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 124/319

• Up to now, we‟ve used global variables

exclusively.• Perl has two ways of creating local variables

– local  and  my

• what you may think of as local (from C/C++)is actually achieved via my.

 my

Page 125: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 125/319

• my creates a new variable scoped to inner most

block – The block may be a subroutine, loop, or bare { }

• variables created with my are not accessible (or

even visible) to anything outside scope.

sub fctn{

 my $x = shift(@_);

… 

}

 print $x; #ERROR!!!

lexical variablesV i bl d l d ith ll d

Page 126: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 126/319

• Variables declared with my are called“lexical variables” or “lexicals” 

• Not only are they not visible outsideblock, they mask globals with samename:

$foo = 10;{

 my $foo = 3;

 print $foo; #prints 3}

 print $foo; #prints 10

Where‟s the scope b ti d l d ithi l i l‟ h

Page 127: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 127/319

• subroutines declared within a lexical‟s scope haveaccess to that lexical

 – this is one way of implementing static variables in Perl

{

 my $num = 20;

sub add_to_num { $num++ }

sub print_num { print “num = $num \n”;} 

}

add_to_num;print_num;

print $num; #ERROR!

local• local does not create new variable

i t d i t l t i ti ( l b l)

Page 128: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 128/319

• instead, assigns temporary value to existing (global)variable

• has dynamic scope, rather than lexical

• functions called from within scope of local variable get thetemporary value

sub fctn { print “a = $a, b = $b\n”; }; 

$a = 10; $b = 20;

{

local $a = 1;

 my $b = 2;fctn();

}

#prints a = 1 b = 20

What to know about scopei t ti ll (l i ll ) d

Page 129: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 129/319

• my is statically (lexically) scoped

 – Look at the actual code. Whatever blockencloses my is the scope of the variable

• local is dynamically scoped – The scope is the enclosing block, plus any

subroutines called from within that block• Almost always want my instead of local

 – notable exception: cannot create lexical

variables such as $_ . Only „normal‟, alpha-numeric variables

 – for built-in variables, localize them.

PrototypesPerl‟s way of letting you limit how you‟ll

Page 130: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 130/319

• Perl‟s way of letting you limit how you‟llallow your subroutine to be called.

• when defining the function, give it the„type‟ of variable you want it to take: 

• sub f1 ($$) {…} 

 – f1 must take two scalars

• sub f2($@) {…}  – f2 takes a scalar, followed by a list

• sub f3(\@$) {…}  – f3 takes an actual array, followed by a

scalar

Prototype conversions

Page 131: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 131/319

• sub fctn($$) { … } 

• fctn(@foo, $bar)

• Perl converts @foo to scalar (ie, takes its

size), and passes that into the function• sub fctn2(\@$) {…} 

• fctn2(@foo, $bar)

• Perl automatically creates reference to@foo to pass as first member of @_ 

Prototype generalitiesif prototype char is: Perl expects:

Page 132: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 132/319

if prototype char is: Perl expects:

 \$ actual scalar variable \@ actual array variable

 \% actual hash variable

$ any scalar value

@ Array or list – „eats‟ rest of params and force list context

% Hash or list – „eats‟ rest of 

params and forces hashcontext

* file handle

& subroutine (name or

Getting around parameters

Page 133: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 133/319

g p

• If you want to ignore parameters, callsubroutine with & character in front

• sub myfunc (\$\$){ … } • myfunc (@array); #ERROR!

• &myfunc (@array); #No error here

Page 134: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 134/319

Objected Oriented Perl

An introduction

Classes in Perl• A class is defined by storing code which

Page 135: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 135/319

y gdefines it in a separate file, and then useing

that file• The file must be named with the name of the

class (starting with an capital letter),

followed by the extension .pm • After the shebang in your „main‟ file, this line

of code:

• use Classname;

• You can then create instances of the classanywhere in your file.

Defining an Object

Page 136: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 136/319

g j

• In Perl, an object is simply a referencecontaining the members of a class.

 – typically, a reference to a hash, but can be

any kind of reference• The reference becomes an object when it

is “blessed” – when you tell Perl the

reference belongs to a certain class.

Page 137: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 137/319

Constructors• Unlike C++ a Constructor in Perl is simply

Page 138: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 138/319

• Unlike C++, a Constructor in Perl is simplyanother subroutine. Typically named „new‟, butyou can give it any name you want.

 package Student;

sub new {

 my $ref = { Name => “”, ID => 0}; bless ($ref, Student);

return $ref;

}

• In this example, don‟t actually have to give $ref any elements. You can define them all in a latersubroutine, if you choose.

Page 139: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 139/319

Arguments to Constructor• (actually, this applies to arguments to any class

th d)

Page 140: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 140/319

method)

• Every time the constructor is called, first argument tofunction is the name of the class.

• Remaining arguments are caller-defined• $obj = new Student (“Bob”, 123); 

• $obj = Student->new(“Bob”, 123); • $obj = Student::new(Student, “Bob”, 123); 

• So, when defining constructor, often see this:sub new{

 my $class = shift; my ($name, $ID) = @_;

 my $ref = {Name => $name, ID => $ID};

 bless ($ref, $class);

return ref;

More Methods• Within the .pm file, any subroutines you declare

become methods of that class

Page 141: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 141/319

become methods of that class.

• For all object methods, first argument is always theobject that the method is being called on. This is alsobeneficial… 

sub name{

 my $ref = shift; my $name = shift;

return $ref->{Name} if $name eq undef;

$ref->{Name} = $name;

}• To call this method:

• $obj->name(“Bob”); 

• Perl translates this to:

One more thing… 

Page 142: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 142/319

• You need to place the following statementat the end of your .pm file:

1;

• This is because the use keyword needs totake something that returns a true value.Perl returns the last statement evaluated.

Be Kind… to One Another  • Note that class variables are not strictly „private‟ in the

Page 143: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 143/319

C++ sense.

• There is nothing preventing the user of your class frommodifying the data members directly, bypassing yourinterface functions.

• Perl‟s general philosophy is “If someone wants to

shoot himself in the foot, who are you to stop him?” • When using other people‟s classes, it‟s almost always

a better idea to use the functions they‟ve given you,and pretend you can‟t get at the internal data. 

• There are, of course, methods you can use to preventusers from doing this. – Really not worth the trouble

 – Significantly beyond scope of this tutorial

Standard Modules• Perl distributions come with a significant

Page 144: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 144/319

Perl distributions come with a significantnumber of pre-installed modules that

you can use in your own programs.• These files are found in system-

specified directories.

• To find where the files are located onyour system, examine the @INC array:

• print “@INC\n”; 

• Gives a listing of all directories that arelooked at when Perl finds a use statement.

Standard Module Example• We‟ll look at a pre defined class that

Page 145: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 145/319

• We ll look at a pre-defined class that

implements Complex-number support inPerl.

• This module is defined in a subdirectory ofthe include path, called Math.

• use Math::Complex;

• The constructor for this class is called make, not new.

• $z = Math::Complex->make(4,3); – Creates an instance of the class Complex.

• $z can be thought to hold the value 4 +

3i

More Math::Complex• Complex.pm is also good enough to overload the

basic mathematical operators to work with

Page 146: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 146/319

basic mathematical operators to work withmembers of the complex class – Overloading operators is beyond the scope of this

lecture – 

 – It also defines a constant i = sqrt(-1);

use Math::Complex;

$z = Math::Complex->make(3,5);

 print “$z\n”; 

$z = $z + 4;

 print “$z\n”; $z = $z – 3*i;

 print “$z\n”; 

Prints:

3 + 5i

7 + 5i

7 + 2i

Privacy?• If you examine the Complex.pm file, you‟ll see

Page 147: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 147/319

that the internal structure of the class is (at least

partially) represented by an array reference called cartesian. Perl will let you modify this

directly:

• $z = Math::Complex->make (3,5);• ${$z->cartesian}[0] = 40;

• Don‟t do that. Instead, use the functions

provided by the class: Re() and Im()• $z->Re(40); #set real part of $z to 40

• $img = $z->Im(); #get img. part of $z

Pragmatic modules

Page 148: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 148/319

• Some modules do not define classes, butrather effect how your perl script is„compiled‟. 

• These modules are called “pragmatic

modules” or just “pragmas”. 

• By convention, they should be all lower-case. (whereas class modules start with a

capital)

• You‟ve already seen two of thesepragmas: warnings and strict.

use an no• Certain pragmas take a list of options, declaring

hi h li i f th t i t

Page 149: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 149/319

which policies of the pragma to import.

• use warnings qw(syntax numeric);• This will only give warnings that fall into the syntax

or numeric categories

• Pragmas can be turned off using nouse warnings;

{

no warnings “digit”; 

#something that would give warnings

}

More Standard Pragmasuse integer;

Page 150: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 150/319

use integer;

 print “10/3=”, 10/3; #prints 3 {

no integer;

 print “10/3=”, 10/3; #3.333333333 }

use constant PI => 4 * atan2 1, 1;

Help on Standard Modules

Page 151: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 151/319

• For documentation for all these modules,you have several resources:

• Unix program perldoc

 – ex, perldoc Math::Complex

• CPAN – http://www.cpan.org

Page 152: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 152/319

A Few More Functions

One more quoting operator

Page 153: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 153/319

• qw//

• Takes a space separated sequence of words,and returns a list of single-quoted words.

 – no interpolation done

• @animals = qw/cat dog bird mouse/;

• @animals („cat‟, „dog‟, „bird‟, „mouse‟); 

• As with q//, qq//, qx//, m//, and s///,you may choose any non-alphanumericcharacter for the delimiter.

map• map EXPRESSION, LIST

BLOCK LIST

Page 154: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 154/319

• map BLOCK LIST

 – evaluate EXPRESSION (or BLOCK) for each valueof LIST. Sets $_ to each value of LIST, much like aforeach loop

 – Returns a list of all results of the expression@words = map {split „ ‟ } @lines; 

 – Set $_ to first member of @lines, run split „ ‟ 

(split acts on $_ if no arg provided), push resultsinto @words, set $_ to next member of @lines,repeat.

More map examples@times = qw/morning afternoon night/;

Page 155: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 155/319

@greetings = map “Good $_ \n”, @times; 

@greetings (“Good morning”, “Goodafternoon”, “Good night”) 

@nums = (1..5);

@doubles = map {$_ * 2} @nums;

@doubles (2, 4, 6, 8, 10);

grep• Similar concept to map (and same syntax)

Page 156: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 156/319

• returns a list of all members of the original list

for which evaluation was true. – (map returns list of all return values of each

evaluation)

• Typically used to pick out lines you want tokeep

@comments = grep {/^\s*#/} @all_lines;

 – picks out all lines beginning with comments – Assigns $_ to each member of @all_lines, then

evaluates the pattern match. If pattern match istrue, $_ is added to @comments

each• Pick out keys and values from a hash.

In scalar context just gets the next key:

Page 157: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 157/319

• In scalar context, just gets the next key:

• while ($key = each %hash){...} foreach $key (keys %hash){...}

• In list context, gets the next key and value of the hash.

• while (($key,$val)= each %hash) {...} foreach $key (keys %hash) {

$val = $hash{$key};

. . .}

• If your list contains more than 2 variables, others getassigned to undef 

glob• glob EXPR

Page 158: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 158/319

g

 – returns EXPR after it has passed through Unix filename

expansion.

• In Unix, ~ is a wild card that means “home directory of this user” 

 – ie, my home directory is ~user23/• Unix also uses * to mean 0 or more of any character,

and ? to mean exactly one of any character.

• This fails: opendir DIR, “~user23”; 

• This doesn‟t: opendir DIR, glob(“~user23”); 

glob returns

Page 159: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 159/319

• If the pattern expansion results in morethan one directory/file, only the first one isreturned in scalar context

 – they‟re all returned in list context. • @files = glob (“*.pl”); 

 – gets a list of all files with a .pl extension in the

current directory.

Page 160: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 160/319

File/Directory manipulation

Opening a File• To read from a file, must use a file handle.

Page 161: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 161/319

 – by convention, all caps

• open a file (for reading):– open FILE, “myfile.txt”; 

 – open file if exists, else return false;

• open file for writing:– open OUTFILE, “>output.txt”; 

 – clobber file if exists, else create new

• open file for appending:– open APPFILE, “>>append.txt”; 

 – open file, positioned at end if exists, else createnew

Page 162: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 162/319

printing to a file

Page 163: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 163/319

• open OUTFILE, “>output.txt”; 

• print OUTFILE “Hello World!\n”; 

• this can be tedious if all outputs are tosame output file.

• select OUTFILE;

 – make OUTFILE the default file handle for allprint statements.

Close your files!

Page 164: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 164/319

• open FILE, “myfile.txt”; • @all_lines = <FILE>;

• close FILE;

• opening another file to the same filehandlewill implicitly close the first one.

 – don‟t rely on this. It‟s not Good Programming

Practice. ™ 

File Test Operators

Page 165: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 165/319

• Test to see if something is true about a file

• full list on page 98 of Camel – exists, readable, zero size, directory, link, text file, etc

if (-e “myfile.txt”){  print “file exists, now opening\n”; 

open FILE, “myfile.txt”; 

}

• can operate on filename or already existingfilehandle

Directory manipulation

Page 166: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 166/319

• directories can be opened, read, created,deleted, much like files.

• take care when doing these operations:

you‟re affecting your directory structure • many of the functions‟ success will depend

on what permissions you have on the

specified directories.

Page 167: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 167/319

Rewind

Page 168: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 168/319

opendir DIR, “.”; $firstfile = readdir DIR;

$secondfile = readdir DIR;

rewinddir DIR;@allfiles = readdir DIR;

Change, Create, and Delete

Page 169: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 169/319

• chdir change working directory.• mkdir create directory (like unix call)

• rmdir remove directory (like unix call)

 – works if and only if directory is empty

chdir “public_html”; 

 mkdir “images”; 

rmdir “temp”; 

Page 170: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 170/319

Page 171: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 171/319

Running external programs

back-ticks, system(), and pipes

system()

Page 172: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 172/319

• Takes a pathname, followed by a list ofarguments.

• Executes the program specified by the

pathname• Returns the return value of the command

that was executed.

 – You may have to shift the result right 8 bits

backticks• Third kind of quoting operator:

Page 173: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 173/319

•Enclose a pathname.• Executes the command specified by thepathname

• Returns the output of that command. – single string in scalar context

 – one line per element in list context

• @files = `ls –al`;• @files contains one file name per element

more on backticks

Page 174: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 174/319

• Just like double quotes, backticks aresubject to interpolation.– $cmd = „prog1.pl‟; 

– $output = `$cmd –h`;• like q// for single quotes, and qq// for

double quotes, backticks can be

represented by qx// – same delimiter rules apply

Pipes

Page 175: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 175/319

• the open function can link a filehandle to arunning process, instead of a file.

• To write to a process, prepend pathname with

the |• To read from a process, append pathname with

the |

• open MAIL, “| /usr/lib/sendmail”; • open LS, “ls –al |”; 

Piping issues

Page 176: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 176/319

• Why pipe instead of using ` `? – with pipes, you can read one line of output at

a time, and terminate process at any time,using close()

• Opening a process for bi-directionalcommunication is more complicated.

 – Involves using the IPC module.

Page 177: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 177/319

Regular Expressions

What are regular expressions?

Page 178: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 178/319

• A means of searching, matching, andreplacing substrings within strings.

• Very powerful

• (Potentially) Very confusing• Fundamental to Perl

• Something C/C++ can‟t even begin to

accomplish correctly

Getting started… • Matching:

• STRING m/PATTERN/;

Page 179: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 179/319

• STRING =~ m/PATTERN/;

 – Searches for PATTERN within STRING.

 – If found, return true. If not, return false. (in scalarcontext)

• Substituting/Replacing/Search-and-replace:• STRING =~ s/PATTERN/REPLACEMENT/;

 – Searches for PATTERN within STRING.

 – If found, replace PATTERN with REPLACEMENT,and return number of times matched

 – If not, leave STRING as it was, and return false.

Matching• *most* characters match themselves. They „behave‟

( di t t t)

Page 180: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 180/319

(according to our text)

if ($string =~ m/foo/){

 print “$string contains „foo‟\n”; 

}

• some characters „misbehave‟. They affect how other characters are treated:

• \ | ( ) [ { ^ $ * + ? .

 – To match any of these, precede them with a backslash:if ($string =~ m/\+/){

 print “$string contains a plus sign\n”; 

}

Substituting

Page 181: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 181/319

• same rules apply to the PATTERN, butnot the REPLACEMENT – No need to backslash the dirty dozen in the

replacement.

 – Except – you must backslash the / no matterwhat, since it‟s the RegExp‟s delimiter  

• greeting =~ s/hello/goodbye/;

• $sentence =~ s/\?/./;• $path =~ s/\\/\//;

Leaning Toothpicks• that last example looks pretty bad.

Page 182: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 182/319

• s/\\/\//; • This can sometimes get even worse:

– s/\/foo\/bar\//\\foo\\bar\\/;

• This is known as “Leaning toothpick” syndrome. • Perl has a way around this: instead of /, use

any non-alphanumeric, non-whitespace

delimiters, just as you can with q() and qq()• s#/foo/bar/#\\foo\\bar\\#;

No more toothpicks• Recall that any non-alphanumeric, non-

whitespace characters can be used as

Page 183: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 183/319

whitespace characters can be used as

delimiters.• If you choose brackets, braces, parens:

 – close each part

 – Can choose different delimiters for second part– s(egg)<larva>;

• If you do use /, you can omit the „m‟ (but not

the „s‟)• $string =~ /found/;

• $sub =~ /hi/bye/; #WRONG!!

Page 184: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 184/319

No binding

Page 185: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 185/319

• If no string is given to bind to (either via =~ or!~), the match or substitution is taken out on $_ 

if (/foo/){

 print “$_ contains the string foo”;  print “\n”; 

}

Interpolation• Variable interpolation is done inside the pattern

match/replace just as in a double-quoted string

Page 186: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 186/319

match/replace, just as in a double quoted string

 – UNLESS you choose single quotes for your delimiters$foo1 = “hello”; $foo2 = “goodbye”; 

$bar =~ s/$foo1/$foo2/;

#same as $bar =~ s/hello/goodbye/;$a = “hi”; $b = “bye”; 

$c =~ s‟$a‟$b‟; 

#this does NOT interpolate. Willliterally search for „$a‟ in $c and replace it with „$b‟ 

Page 187: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 187/319

Now we‟re ready • Up to this point no real „regular expressions‟

Page 188: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 188/319

Up to this point, no real regular expressions  

 – pattern matching only• Now we get to the heart of the beast

• recall 12 „misbehaving‟ characters: 

– \ | ( ) [ { ^ $ * + ? .• Each one has specific meaning inside of

regular expressions.

 – We‟ve already seen 3 of them… 

Alternation• simply: “or” 

Page 189: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 189/319

• use the vertical bar: | – similar (logically) to || operator

• $string =~ /(Paul|Justin)/

 – search $string for “Paul” or for “Justin”  – return first one found in $1

• /Name=(Robert(o|a))/

 – search $_ for “Name=Roberto” or “Name=Roberta”  – return either Roberto or Roberta in $1

 – (also returns either o or a in $2)

Capturing and Clustering

W ‟ l d l f thi b t

Page 190: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 190/319

• We‟ve already seen examples of this, butlet‟s spell it out: 

• Anything within the match enclosed inparentheses are returned („captured‟) in thenumerical variables $1, $2, $3

• Order is read left-to-right by *Opening*parenthesis.– /((foo)=(name))/

 – $1 “foo=name”, $2“foo”, $3“name”; 

Clustering

• Parentheses are also used to „cluster‟ parts of 

Page 191: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 191/319

the match together. – similar to the function of parens in mathematics

• /prob|n|r|l|ate/

 – matches “prob” or “n” or “r” or “l” or “ate” 

• /pro(b|n|r|l)ate/

 – Matches “pro”, followed by one of b, n, r or l,followed by “ate” 

 – Matches “probate” or “pronate” or “prorate” or “prolate” 

 – $1 equals b, n, r or l if match occurs

Clustering without Capturing• For whatever reason, you might not want to

Page 192: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 192/319

„capture‟ the matches, only cluster somethingtogether with parens.

• use (?: ) instead of plain ( )

• in previous example:• /pro(?:b|n|r|l)ate/

 – matches “probate” or “pronate” or “prorate” or “prolate” 

 – this time, $1 does not get value of b, n, r, or l

Beginnings strings

• ^ matches the beginning of a string

Page 193: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 193/319

matches the beginning of a string

• $string = “Hi Bob. How goes it?” 

• $string2 = “Bob, how are you?\n”; 

• $string =~ /^Bob/;

 – returns false

• $string2 =~ /^Bob/;

 – returns true

Ends of Strings• $  matches the end of a string

• $s1 = “Go home”;

Page 194: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 194/319

• $s1 = Go home ; 

• $s2 = “Your home awaits”; 

• $s1 =~ /home$/;

 – true

• $s2 =~ /home$/;

 – false

• $ does not consider terminating newline.• “foo bar\n” =~ /bar$/; 

 – true

*Some* meta-characters• For complete list, see pg 161 of Camel

• \d   any digit: 0 – 9

Page 195: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 195/319

–\D 

any non-digit• \w  any „word‟ character: a-z,A-Z,0-9,_ 

– \W   any „non-word‟ character  

• \s  any whitespace: “ ”, “\n”, “\t” – \S  any non-whitespace character

• \b  a word boundary – this is “zero-length”. It‟s simply “true” when at the

boundary of a word, but doesn‟t match any actualcharacters

– \B  true when not at a word boundary

The . Wildcard

Page 196: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 196/319

• A single period matches “any character”. – Except the new line

• /filename\..../ – matches filename.txt, filename.doc,

filename.exe, or any other 3 characterextension

Quantifiers

• “How many” of previous characters to match 

Page 197: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 197/319

y p

• *  0 or more

• +  1 or more

• ?  0 or 1

• {N}  exactly N times

• {N, }  at least N times

• {N, M} 

between N and M times

Quantifier examples

• /a*/ match 0 or more letter a‟s

Page 198: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 198/319

• /a*/  match 0 or more letter a s 

 – matches „a‟,„aa‟,„aaa‟,„‟,„bb‟ 

• /((?:foo)+)/  match 1 or more “foo”, and

saves them all in $1 – matches „foob‟,„foobfoob‟,„bfoofoofoo‟ 

•  /o{2}/  matches 2 letter o‟s  – matches „foo‟, „foooooo‟ 

•  /(b{3,5})/  matches 3, 4, or 5 letter b‟s, andsaves what it matched in $1 – matches „bbb‟, „abbbba‟, „abbbbbba‟ 

Greediness

• All quantifiers are „greedy‟ by nature They

Page 199: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 199/319

• All quantifiers are greedy by nature. Theymatch as much as they possibly can.

• They can be made non-greedy by adding a? at the end of the quantifier

• $string = “hello there!” 

• $string =~ /e(.*)e/;

 – $1 gets “llo ther” 

• $string =~ /e(.*?)e/;

 – $1 gets “llo th”; 

Character classes• Use [ ] to match characters that have a

certain property

Page 200: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 200/319

certain property

 – Can be either a list of specific characters, or arange

• /[aeiou]/

 – search $_ for a vowel

• /[a-nA-N]/

 – search $_ for any characters in the 1st half of the

alphabet, in either case• /[0-9a-fA-F]/

 – search $_ for any „hex‟ digit. 

Character class catches• use ^ at very beginning of your character class

to negate it

Page 201: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 201/319

g

• /[^aeiou]/ – Search $_ for any non-vowel

 – Careful! This matches consonants, numbers,

whitespace, and non-alpha-numerics too!• . wildcard loses its specialness in a characterclass– /[\w\s.]/

 – Search $_ for a word character, a whitespace, or adot

• to search for „]‟ or „^‟, make sure you backslash

th i h t l

Page 202: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 202/319

More Regular Expressions

List vs. Scalar Context for m// 

• We said that m// returns „true‟ or „false‟

Page 203: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 203/319

We said that m// returns true or false

in scalar context. (really, 1 or 0).

• In list context, returns list of all matchesenclosed in the capturing parentheses.– i.e.: $1, $2, $3, etc are still set

• If no capturing parentheses, returns (1)

• If m// doesn‟t match, returns ()

Modifiers

Page 204: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 204/319

• following the final delimiter, you can placeone or more special characters. Each onemodifies the regular expression and/or thematching operator

• full list of modifiers on pages 150 (for m//)and 153 (for s///) of Camel

 /i Modifier

Page 205: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 205/319

• /i 

case insensitive matching.• Ordinarily, m/hello/ would not match “Hello.” 

• However, this match *does* work:

– print “Yes!” if “Hello” =~ m/hello/i; • Works for both m// and s///

 /s Modifier• /s Treat string as a single line

Page 206: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 206/319

• Ordinarily, the . wildcard matches any characterexcept the newline

• If the /s modifier is provided, Perl will treat your

RegExp as a single line, and therefore the . 

wildcard will match \n characters as well.

• Also works for both m// and s///

• “Foo\nbar\nbaz” =~ m/F(.*)z/; 

 – Match fails

• “Foo\nbar\nbaz” =~ m/F(.*)z/s; 

 – Match succeeds - $1  “oo \nbar\ nbaz” 

 /m Modifier

• /m   Treat string as containing multiple

Page 207: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 207/319

lines• As we saw last week, ^ and $ match

“beginning of string” and “end of string”

respectively.• if /m provided, ^ will also match right after a\n, and $ will match right before a \n

 – in effect, they match the beginning or end of a“line” rather than a “string” 

• Yet again, works on both m// and s///

 /x Modifier• /x  Allow formatting of pattern match

• Ordinarily, whitespace (tabs, newlines, spaces) inside

Page 208: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 208/319

Ordinarily, whitespace (tabs, newlines, spaces) inside

of a regular expression will match themselves.• with /x, you can use whitespace to format the pattern

match to look better

• m/\w+:(\w+):\d{3}/; – match a word, colon, word, colon, 3 digits

• m/\w+ : (\w+) : \d{3}/; – match word, space, colon, space, word, space, colon,

space, 3 digits (literal interpretation of whitespace in searchstring)

• m/\w+ : (\w+) : \d{3}/x; – match a word, colon, word, colon, 3 digits

 – Makes it look pretty, but who cares?

More /x Fun• /x also allows you to place comments in yourregexp

Page 209: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 209/319

• Comment extends from # to end of line, just asnormal

m/ #begin match

\w+ : #word, then colon

(\w+) #word, returned by $1

: \d{3} #colon, and 3 digits

/x #end match

• Do not put end-delimiter in your comment

• yes, works on m// and s/// 

Page 210: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 210/319

More m//g• Scalar context• initiate a „progressive‟ match • Perl will remember where your last match on this

Page 211: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 211/319

• Perl will remember where your last match on thisvariable left off, and continue from there

$s = “abc def ghi”;for (1..3){

 print “$1 ” if $s =~ m/(\w+)/;} – abc abc abc

for (1..3){

 print “$1 ” if $s =~ m/(\w+)/g;} – abc def ghi

 /g Modifier (for s///)

• global replacement

Page 212: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 212/319

•/g

  global replacement

• Ordinarily, only replaces first instance ofPATTERN with REPLACEMENT

• with /g, replace all instances at once.$a = „$a / has / many / slashes /‟; 

$a =~ s#/#\\#g;

• $a now „$a \ has \ many \ slashes \ ‟ 

Return Value of s/// 

• Regardless of context, s/// always

Page 213: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 213/319

returns the number of times it successfullysearch-and-replaced

• If search fails, didn‟t succeed at all, so

returns 0, which is equivalent to false• unless /g modifier is used, s/// will

always return 0 or 1.

• with /g, returns total number of globalsearch-and-replaces it did

Page 214: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 214/319

Modifier notes

• Modifiers can be used alone or with any other

Page 215: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 215/319

Modifiers can be used alone, or with any othermodifiers.

• Order of more-than-one modifiers does notmatter

• s/$a/$b/gixs;

 – search $_ for $a and replace it with $b. Search

globally, ignoring case, allow whitespace, and allow

. to match \n.

A Bit More on Clustering

• So far, we know that after a pattern match, $1,

Page 216: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 216/319

So far, we know that after a pattern match, $1,$2, etc contain sub-matches.

• What if we want to use the sub-matches whilestill in the pattern match?

• If we‟re in the replacement part of s///, no

problem – go ahead and use them:• s/(\w+) (\w+)/$2 $1/; # swap two words

• if still in match, however…. 

Page 217: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 217/319

Page 218: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 218/319

,Replace?

• Much like character classes, tr/// takes a

list or range of characters.

Page 219: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 219/319

list or range of characters.

• tr/a-z/A-Z/;

 – replace any lowercase characters withcorresponding capital character.

• TAKE NOTE: SearchList andReplacementList are NOT REGULAREXPRESSIONS

 – attempting to use RegExps here will give youerrors

• Also, no variable interpolation is done in

tr/// Notes

• In either context, tr/// returns the number

Page 220: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 220/319

of characters it modified.• if no binding string given, tr/// operates

on $_ , just like m// and s///

• tr/// has an alias, y///. It‟s deprecated,but you may see it in old code. 

tr/// Notes• if Replacement list is shorter than Search

list, final character repeated until it‟s long

Page 221: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 221/319

enough– tr/a-z/A-N/; 

 – replace a-m with A-M.

 – replace n-z with N• if Replacement list is null, repeat Search list

 – useful to count characters 

• if Search list is shorter than Replacementlist, ignore „extra‟ characters is Replacement 

tr/// Modifiers• /c  Compliment the search list

Page 222: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 222/319

 – „real‟ search list contains all characters *not* ingiven searchlist

• /d   Delete characters with no

corresponding characters in the replacement– tr/a-z/A-N/d; 

 – replace a-n with A-N. Delete o-z.

• /s  Squash duplicate replaced characters

 – sequences of characters replaced by samecharacter are „squashed‟ to single instance of character

Page 223: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 223/319

CGI Programming

What is “CGI”? 

• Common Gateway Interface

Page 224: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 224/319

• A means of running an executableprogram via the Web.

• CGI is not a Perl-specific concept.Almost any language can produce CGIprograms

 – even C++ (gasp!!)

• However, Perl does have a *very* niceinterface to creating CGI methods

How Does it Work?• A program is created, like normal.

• The program must be made user-executable

Page 225: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 225/319

• A user visits a web page.• The web browser contacts the server where the

CGI program resides, and asks it to run theprogram

 – passes Parameters to the program• similar to command line arguments

• The server runs the program with the parameterspassed in

• The server takes the output of the program andreturns it to the web browser.

• The web browser displays the output as anHTML page

Forms

Page 226: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 226/319

• Most (not all) CGI scripts are contactedthrough the use of HTML forms.

• A form is an area of a web page in whichthe user can enter data, and have that

data submitted to another page.• When user hits a submit button on the

form, the web browser contacts the script

specified in the form tag.

Creating a Form <form method=“post” action=“file.cgi”>  

… 

Page 227: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 227/319

 <input type=“submit” value=“Submit Form”>  

 </form> 

• Method attribute specifies how parameters are passed to

the CGI program. “post” means they‟re passed in theHTTP header (and therefore aren‟t seen anywhere). “get”means they‟re passed through the address bar in the webbrowser.

• Action attribute specifies which program you want theweb browser to contact.

• <input> is a tag used to accept User data.

type=“submit” specifies a Submit button. When user 

Form Input Types• Many different ways of getting data from user. Mostspecified by <input> tag, type specified by type attribute

Page 228: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 228/319

• text

a text box• checkbox a check box

• radio a Radio button

• password password field

 – (text box, characters display as ******)• hidden hidden field (nothing displayed in browser)

• submit Submit button. Submits the form

• reset Reset button. Clears form of all data.

• button A button the user can press – (usually used w/ javaScript. *shudder*)

• file field to upload a file

• image an image user can click to submit form

Other Attributes of <input> 

• name  name of input field.

Page 229: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 229/319

• value  value returned from checks &

radios; text of submits and buttons; contentsof text, password, and hidden

• size  width of text or password

• checked   radio or checkbox „turned on‟ 

•src

  URL of an image

Inputs that Don‟t Use <input> 

Page 230: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 230/319

• <textarea> - Multi-line text field. Youcan specify rows and cols attributes

• <select> - create a drop-down menu.

– <option value=“…”> Options in the dropdown menu.

. .what?

• Now, we can write a CGI program that

Page 231: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 231/319

takes those inputs and *does stuff* withthem.

• This is still a perl script. Therefore, still

need the shebang as top line of the code.• Next, need to include all the CGI

methods. These are stored in CGI.pm

 – As you may guess, TMTOWTDI.• use CGI;

• use CGI “:standard”; 

Object-Oriented• CGI.pm actually defines a class. Therefore,

if you use CGI; you can then do

Page 232: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 232/319

• $q = new CGI;

• and access the CGI subroutines as methodsof $q .

• print $q->start_html();

• This allows you to maintain multiple „states‟

using more than one instance of the CGIclass

• Very useful for complicated programs

Function-Oriented• Alternatively, you can import a set of subroutines to be

called directly, without the need to declare an object.

Page 233: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 233/319

• Tell Perl which subroutines to import by given aquoted list in the use statement:• use CGI (“start_html”, “end_html”, “header”); 

• CGI.pm defines sets of these functions. Most

common is the „standard‟ set: • use CGI “:standard”; 

• For a full list of which functions are in which sets,

examine the CGI.pm file, looking at the variable%EXPORT_TAGS 

• Now, you can call all the CGI subroutines directly,without declaring any objecs

Outputting from CGI

Page 234: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 234/319

• Just as CGI program took „input‟ from user via web browser, it outputs back to uservia web browser as well.

• STDOUT is redirected to the web browser

that contacted it.• This means you don‟t have to learn any

new output functions. print() will now

throw data to the web browser.

Beginning a CGI Program

Page 235: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 235/319

#!/usr/local/bin/perluse CGI “:standard”; 

 print header(“text/html”); 

• header() prints HTTP header to webbrowser. Argument is MIME type of data.Defaults to text/html, so you can usually

 just leave the argument out.

Now Create your Output

Page 236: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 236/319

• Remember, you‟re building an HTML page inthe output. So you must follow the HTMLformat:

 print “<html><head>”, “<title>My CGI Program</title> \n”, 

“</head><body> \n”; 

• CGI.pm gives you a better way to do this.We‟ll get to it soon. 

Where‟d Those Inputs Go? 

• They were passed into the CGI program asparameters. You can retrieve them using

Page 237: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 237/319

p gthe param() function.

• Called in list context w/ no argument,returns names of all parameters.

• Called in scalar context, takes name of oneparameter, and returns value of thatparameter

• Called in list context w/ an argument,returns array of all values for that parameter(ie, for checks and radios)

Page 238: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 238/319

CGI.pm HTML Shortcuts

Page 239: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 239/319

• CGI.pm gives you methods to create HTML codewithout actually writing HTML.

• most HTML tags are aliased to CGI functions.

• unpaired tags:– print br(); # sends <br> to browser

– print p; # sends <p> to browser

• paired tags:

– print b(“Bold text”); #<b>Bold text</b>  – print i(“Italic”); #<i>Italic</i>  

More shortcuts• For tags with attributes, place name/value

attributes in a hash reference as the first

Page 240: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 240/319

argument. The string enclosed in tag is thesecond argument. Ex:a({href=>“sample.html”, target=>“top”}, 

“Sample file”); 

• Produces:

• <a href=“sample.html”target=“top”>Sample file</a>  

• You may think this is needless amounts of extralearning, with no time or length benefits – You‟re probably right. In this case. 

start_html()• Can take one parameter, the title.

• print start_html(“My title”); –

Page 241: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 241/319

 <html><head><title>My title </title></head><body> 

• Can also take named parameters, withattributes to give to <body> tag:

• print start_html (-title=>“MyTitle”, - bgcolor=>“Red”); – <html><head><title>My title </title></head><body bgcolor=“Red”>  

• print end_html;– </body></html> 

HTML Form Shortcuts• For full list of Form shortcuts, seehttp://stein.cshl.org/WWW/software/CGI/#forms

• Or examine the %EXPORT_TAGS variable in CGI.pm

Page 242: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 242/319

• Each one takes parameters as name/value pairs.Name starts with a dash. Most parameters areoptional

• startform(- method=>“post”, -action=> “foo.cgi”) 

 – default method is post. default action is current script• this is *very* beneficial.

• produces: <form method=“post” action=“foo.cgi”>  

• endform(); # produces </form> 

Input Shortcuts

Page 243: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 243/319

• textfield(-name=>“MyText”, -default=>“This is a text box”) 

– <input type=“text” name=“MyText”

value=“This is a text box”>  

• All HTML Form input shortcuts are similar.Again, see

http://stein.cshl.org/WWW/software/CGI/#formsfor full list and description.

Programmer Beware

Page 244: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 244/319

• “default” in input methods is value used*first* time script is loaded only. After that,they hold the values they had the last time

the script was run.• to override (ie, force default value to

appear), set parameter -override=>1 

inside input method:

• textfield(-name=>“foo”, -default=>“bar”, -override=>1);

Avoid Conflicts• Some HTML tags have same name as internal Perl

functions. Perl will get very confused if you try to usethe CGI shortcut methods to print these tags… 

///

Page 245: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 245/319

• <tr>   – table row. conflicts with tr/// – use Tr() or TR() instead

• <select>   – dropdown list. conflicts withselect(). – use Select() instead

• <param> - pass parameters to Java applet – conflicts with param().

 – use Param() instead• <sub> - Make text subscripted. Conflicts with sub 

keyword. – Use Sub() instead

Running CGI on CS machines• The CGI-enabled server in the CS Departmentis cgi2.cs.rpi.edu

Page 246: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 246/319

• To run your scripts on cgi2.cs – set shebang: #!/usr/bin/env perl

 – make file user-executable

 – put the file in public.html/cgi-bin directory – Make sure public.html and cgi-bin are world-

executable

 – go to http://cgi2.cs.rpi.edu/~yourID/cgi-bin/script.cgi

• If all goes well, your script‟s output will bedisplayed.

• If all does not go well, you‟ll get HTTP 500 

Debugging• Debugging a CGI program can be a very frustratingtask.

• If there are any errors whatsoever, the web browserwill simply display  

i h h l f l i f i

Page 247: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 247/319

500 Internal Server Errorwith no helpful information.• One solution is to run the program from the command

line.• CGI.pm will ask you for name=value pairs of

parameters. Enter each name and value of theparameters, separated by newline. Then press CTRL-D. – (some newer versions of CGI.pm don‟t support this – pass

name=value pairs on command-line instead)• This way, you get the compiler errors, and you cansee the „pure‟ HTML output of your CGI script. 

• The other method is to examine the server‟s error logs.

Lastly… • Well, lastly for today anyway.

• One common method of CGI programming is to make both theform and the response all in one script. Here‟s how you do

th t

Page 248: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 248/319

that… #!/usr/bin/env perl -w

use CGI “:standard”; 

print header;

if (!param()){

 print start_html(-title => “Here‟s a form”); 

 print startform; #no action

#create your form here… } else {

 print start_html(-title=> “Here‟s the result”); 

#display the results of the submitting form 

Page 249: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 249/319

More CGI Programming

Multiple Submits

Cookies

EmailingFile Uploading

Deciding Where to Go

Wh if h h

Page 250: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 250/319

• What if you want to have more than onefunctionality on your form? In otherwords, have more than one button the

user can push.• The name and value of the submit

button are passed as params

• This is useful.

Multiple Submits• Just as you can have many different text fields orcheckboxes, you can have different submit buttons

• Make sure you give each submit a different name.

O l th b it b tt th t i d ill b d

Page 251: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 251/319

• Only the submit button that is pressed will be passedas a parameter.

• Check to see if this parameter exists.

<input type=submit name=Submit1 value=“GoHere!”> 

<input type=submit name=Submit2 value=“GoThere!”> 

if (param(„Submit1‟){ … }elsif (param(„Submit2‟){ … } 

else{ … } 

File Uploading• Another input method we did not talk about is file-

uploading

T fil l di f t t i l ki d

Page 252: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 252/319

• To use file-uploading feature, must use a special kindof HTML form: – Add ENCTYPE=“multipart/form-data” to <form>

 – Or, in Perl, use start_multipart_form() instead of start_form()

• Html: <input type=„file‟ name=„uploaded‟> 

• Perl: filefield(-name=>„uploaded‟) 

• Creates a field in which user can enter name of file tosend to server. Also creates „Browse‟ button to search

local machine.• User enters name or path of a file to upload.

• When form submitted, CGI script can then get this file

Getting the File• To get the name of the file user wants to upload, use

param() function.

$fil („ l d d‟)

Page 253: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 253/319

• $file = param(„uploaded‟); • If you use $file as a string, it will be the name of the

file. If you use $file as a filehandle, it will be a link tothe actual file.

print “Contents of file $file are:<br>\n”; 

foreach $line <$file>{

print “$line<br>”; 

}

That‟s Great for Text Files… • But users can upload any kind of file.

• Need to find out what kind of file it was.

l dI f () f ti R t f t

Page 254: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 254/319

• uploadInfo() function. Returns reference toa hash containing info about the file.

• $file = param(„uploaded‟); 

• $info = uploadInfo($file);

• $type = $info->{„Content-Type‟}; 

• $type may contain “text/html”, “text/plain”,“image/jpeg”, etc etc… 

If File is not Text• Need function to read from binary files.

• read($filename, $buffer, $size)

$fil fil h dl t d

Page 255: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 255/319

 – $filenamefilehandle to read – $bufferscalar in which to store data

 – $sizemax number of bytes to read

 – returns number of bytes read

$file = param(„uploaded‟); 

open UPLOAD, “>binary.jpg”; 

while ($num=read($file,$buf,1024))

{ print UPLOAD $buf; }

close UPLOAD;

Emailing from your CGI Script

I t lit thi t

Page 256: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 256/319

• In actuality, you can use this process toemail from any Perl program.

• Note that this will be a Unix-specific.

sendmail

b b ili N

Page 257: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 257/319

• barebones emailing program. Nofriendly user interface whatsoever.

• standard with most Unix distributions.

• We need to run it with the –t flag. Thistells the program to search the messagefor the To:, Cc:, Bcc:, etc… 

• For more information, man sendmail

Page 258: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 258/319

Put Them Together

open (MAIL, “|/usr/lib/sendmail –t”) ||

die “Cannot begin mail program”;

Page 259: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 259/319

die “Cannot begin mail program”; 

print MAIL “From: lallip\@cs.rpi.edu\n”; 

print MAIL “To: president\@rpi.edu\n”; 

print MAIL “Subject: I want a raise!\n”; print MAIL “You know, Dr. J, I‟m not quite

sure this is really worth it. …\n”; 

close MAIL;

Cookies

• Love them or hate them, they exist.

And o ‟ll learn ho to se them

Page 260: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 260/319

 And you‟ll learn how to use them.  – learning to use them responsibly is your

own task.

• A cookie is a (usually very small) pieceof text that a server sends to a webbrowser for later retrieval.

• Can be used to „track‟ a user‟spreferences, or other information userhas told the server.

To Set a Cookie• Create the cookie

• cookie() function. Takes many (mostlyoptional) parameters:

Page 261: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 261/319

optional) parameters:

 –  -name=> Name of the cookie

 –  -value=> Value of the cookie  – can be a scalar,

array reference, or hash reference –  -expires=> Expiration date/time of the cookie

 –  -path=> Path to which cookie will be returned

 – -domain=> Domain to which cookie will bereturned

 –  -secure=> 1 if cookie returned to SSL only

Cookie Expiration• Expires: absolute or relative time forcookie to expire – +30s in 30 seconds

10 i 10 i t

Page 262: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 262/319

 – +10m in 10 minutes

 – +1h in one hour

 – -d yesterday (ASAP)

 – now immediately – +3M in 3 Months

 – +10y in 10 Years

 – Wed, 05-Dec-2001 18:00:00 GMT

OnWednesday, 12/5/2001 at 6pm GMT.

Cookie Path

• „region‟ of server to check before

sending back the cookie

Page 263: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 263/319

sending back the cookie.• If I set a cookie with path = /perl/f01/ 

• Then only CGI scripts in /perl/f01 (andits subdirectories) will receive thecookie.

• By default, path is equal to the path ofthe current CGI script.

• To send cookie to all CGI scripts onserver, specify path = / 

Cookie Domain• domain (or partial domain) to send cookie

back to.

• must contain at least 2 periods (so can‟t send

Page 264: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 264/319

• must contain at least 2 periods (so can t sendcookie to all .com domains)

• if I set cookie domain = .rpi.edu, cookie will besent to scripts on www.rpi.edu,www.cs.rpi.edu, cgi.cs.rpi.edu, etc

• if set to .cs.rpi.edu, cookie only sent towww.cs.rpi.edu, cgi.cs.rpi.edu, cgi2.cs.rpi.edu,etc

• if set to www.cs.rpi.edu, cookie sent only topages on www.cs.rpi.edu

• Note that both domain and path must match

Cookie Created, Now Set it.

$cookie = cookie( … ); 

print header( cookie=>$cookie);

Page 265: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 265/319

print header(-cookie=>$cookie);

• To set more than one cookie, use arrayreference

$cookie1 = cookie (…); 

$cookie2 = cookie (…); 

print header(-cookie=>[$cookie1,

$cookie2]);

Read the Cookies

• Once again, use the cookie() function.

Page 266: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 266/319

• This time, just give the name:

$mycookie = cookie(„lallip‟); 

• $mycookie now has value of cookie withname lallip.

Perl Database Interface (DBI)

Outline

Page 267: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 267/319

• Introduction to DBI

• Working with DBI

• Manipulating a Database with DBI

• DBI and the Web

• DBI Utility Functions

• MySQL Server

• Internet and World Wide Web Resources

Introduction to DBI

• Uses

Page 268: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 268/319

 – E-mail, purchasing online, storing files

• Distributed Applications

 – Several machines get data from one database

 – That data is then shown on one machine

• Called the client

Introduction to DBI (cntd.)

• Perl DBI

I f id if ll

Page 269: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 269/319

 – Interface provides uniform access across alldatabases

 – Handles – objects in the interface

• Diver handles – encapsulate the driver, makedatabase handles

• Database handles – encapsulate specific SQLstatements

• Statement handles – are created by databasehandles

Working with DBI

• DBI

M b i d i h lid ODBC

Page 270: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 270/319

 – Must be registered with a valid ODBC sourcebefore use

$9

8 use DBD::ODBC;

7 use DBI;

6 use strict;

5 use warnings;

4

3 # Program to query a database and display contents in a table 

2 # Fig. 15.18: fig15_18.pl 

1 #!/usr/bin/perl 

Loads the DBI 

module and base

driver

Page 271: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 271/319

fig15_18.pl

29

28 $sth->finish();

27 $dbh->disconnect();

26 warn( $DBI::errstr ) if $DBI::err;

25 # Check to see if fetch terminated early 

24

23 }

22  write();

21 while ( @array = $sth->fetchrow_array() ) {

20

19 my @array;

18

17 die( "Cannot execute statement: ", $sth->errstr(), "\n" );16 $sth->execute() or 

15

14 die( "Cannot prepare statement: ", $dbh->errstr(), "\n" );

13 my $sth = $dbh->prepare( q { SELECT * FROM employee } ) or 

12

11 die("Could not make connection to database: $DBI::errstr" );

10 my $dbh = DBI->connect( "DBI:ODBC:employeeDB", "", "" ) or 

Creates a

statement 

handle

Calls the execute 

method of the statement

handle

Displays the arrays in the

format programmed

0004 Michael Black 1965 222-44-88880001 Jim Blue 1943 999-85-3698

0002 Kate Green 1977 111-21-74540003 Wendy White 1959 000 84 3196

33 .

32 $array[ 0 ], $array[ 1 ], $array[ 2 ], $array[ 3 ], $array[ 4 ]

31 @<<<<<<@<<<<<<<<<@<<<<<<<<<<@<<<<<@<<<<<<<<<<<

30 format STDOUT = The format to display an array

Page 272: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 272/319

fig15_18.pl

Program Output

0003 Wendy White 1959 000-84-3196 

Working with DBIFunction Name Return Type Description

fetchrow_array array Returns a single row in an array.

fetchrow arrayref array ref Returns a single row in an array

Page 273: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 273/319

fetchrow_arrayref array ref Returns a single row in an array

reference.

fetchrow_hashref hash ref Returns a single row in a hash

reference with fieldname value

pairs.

fetchall_arrayref array ref Returns the whole result set in areference to an array. The array

consists of references to arrays

that hold the rows of data.

Fig. 15.19 Functions for extracting the results of a query. 

Manipulating a Database withDBI

• How to:

Add d

Page 274: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 274/319

 – Add records

 – Delete records

 – Update records

10 my $dbh = DBI->connect( "dbi:ODBC:employeeDB", "", "",9

8 use DBD::ODBC;

7 use DBI;

6 use strict;

5 use warnings;

4

3 # Program to insert a new record into the database. 2 # Fig. 15.20: fig15_20.pl 

1 #!/usr/bin/perl 

If there are connection

Page 275: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 275/319

fig15_20.pl

30

29 $dbh->do( $querystring );

28 # Execute the statement 

27

26 '$newbirthyr','$newsoc' );";

25 ( '$newemploy','$newfirst','$newlast',

24 my $querystring = "INSERT INTO employee VALUES

23

22 chomp( my $newsoc = <STDIN> );

21 print( "Please enter your social security number: " );

20 chomp( my $newbirthyr = <STDIN> );

19 print( "Please enter your year of birth: " );

18 chomp( my $newlast = <STDIN> );17 print( "Please enter your last name: " );

16 chomp( my $newfirst = <STDIN> );

15 print( "Please enter your first name: " );

14 chomp( my $newemploy = <STDIN> );

13 print( "Please enter your employee ID: " );

12

11 { RaiseError => 1 } ); problems RaiseError 

will kill the program and

generate a message

Takes in all the data fieldsto be added to the database

Inserts the valuesinto the database

39

38 my @array;

37

36 print( "\n" );

35

34 $sth->execute();

33

32 my $sth = $dbh->prepare( q{ SELECT * FROM employee } );

31 # Now print the updated database 

Prints the updated database

Page 276: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 276/319

fig15_20.pl

52 .

51 $array[ 0 ], $array[ 1 ], $array[ 2 ], $array[ 3 ], $array[ 4 ]

50 @<<<<<<@<<<<<<<<<@<<<<<<<<<<@<<<<<@<<<<<<<<<<<

49 format STDOUT =

48

47 $dbh->disconnect();

46 $sth->finish();

45 warn( $DBI::errstr ) if $DBI::err;

44 # Clean up 

43

42 }

41  write();

40 while ( @array = $sth->fetchrow_array() ) {

Closes the table and the

connection to the database

Please enter your employee ID: 0005

Please enter your first name: OrinthalPlease enter your last name: OrangePlease enter your year of birth: 1947Please enter your social security number: 999-88-7777

0004 Michael Black 1965 222-44-88880001 Jim Blue 1943 999-85-36980005 Orinthal Orange 1947 999-88-77770002 Kate Green 1977 111-21-7454

0003 Wendy White 1959 000-84-3196

Page 277: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 277/319

fig15_20.pl 

Program Output

10 my $dbh = DBI->connect( "dbi:ODBC:employeeDB", "", "",9

8 use DBD::ODBC;

7 use DBI;

6 use strict;

5 use warnings;

4

3 # Program to delete a record from the database 2 # Fig. 15.21: fig15_21.pl 

1 #!/usr/bin/perl 

Page 278: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 278/319

fig15_21.pl

29

28 $sth->execute();

27

26 my $sth = $dbh->prepare( q { select * FROM employee } );

25

24 }

23 $dbh->do( $query );

22  print( "$query \n\n" );

21 "WHERE EmployeeID = '$IDdel'";

20 my $query = "DELETE FROM employee " .

19 if ( $choice eq 'Y' || $choice eq 'y' ) {

18

17 chomp( my $choice = <STDIN> );

16 print( "Delete this record: ($IDdel)? (Y/N) " );

15 chomp( my $IDdel = <STDIN> );

14 "you wish to delete: " );

13 print( "Enter the Employee ID number of the record ",

12

11 { RaiseError => 1 } );

10 my $dbh DBI >connect( dbi:ODBC:employeeDB , , ,

Prompts the user for which

employee they want to delete

Confirms the delete

37 warn( $DBI::errstr ) if $DBI::err;

36 # Clean up 

35

34 }

33  write( STDOUT );

32 while ( @array = $sth->fetchrow_array() ) {

31

30 my @array;

Displays the table in

the correct format

Page 279: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 279/319

fig15_21.pl44 .

43 $array[ 0 ], $array[ 1 ], $array[ 2 ], $array[ 3 ], $array[ 4 ]42 @<<<<<<@<<<<<<<<<@<<<<<<<<<<@<<<<<@<<<<<<<<<<<

41 format STDOUT =

40

39 $sth->finish();

38 $dbh->disconnect();

Enter the Employee ID number of the record you wish to delete:

0005Delete this record: (0005)? (Y/N) yDELETE FROM employee WHERE EmployeeID = '0005'

0004 Michael Black 1965 222-44-88880001 Jim Blue 1943 999-85-36980002 Kate Green 1977 111-21-74540003 Wendy White 1959 000-84-3196

Page 280: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 280/319

fig15_21.pl 

Program Output

10 my $dbh = DBI->connect( "dbi:ODBC:employeeDB" "" ""9

8 use DBD::ODBC;

7 use DBI;

6 use strict;

5 use warnings;

4

3 # Program to update a record in the database. 2 # Fig. 15.22: fig15_22.pl 

1 #!/usr/bin/perl 

Page 281: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 281/319

fig15_22.pl

26

25 chomp( my $change = <STDIN> );

24 print( "? " );23 print( "5. Social Security Number.\n" );

22 print( "4. Year of Birth.\n" );

21 print( "3. Last name.\n" );

20 print( "2. First name.\n" );

19 print( "1. Employee Identification. \n" );

18 print( "Which value would you like to change:\n" );

1716 chomp( my $ID = <STDIN> );

15

14 "you wish to change: " );

13 print( "Enter the Employee ID number of the record ",

12

11 { RaiseError => 1 } );

10 my $dbh = DBI >connect( dbi:ODBC:employeeDB , , ,

Finds out the correct data from the

user. What should be changed and

what the new data should be.

37 elsif ( $change == 3 ) {

36 }

35  print( "Enter the employee's new First name: " );

34 $field = "FirstName";

33 elsif ( $change == 2 ) {

32 }

31  print( "Enter the employee's new employee number: " );

30 $field = "EmployeeID";

29 if ( $change == 1 ) {28

27 my $field;

Determines the

proper field that the

user wants to change

Page 282: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 282/319

fig15_22.pl

57

56 '$newvalue' WHERE EmployeeID = '$ID'";

55 my $query = "UPDATE employee SET $field =

54 chomp( my $newvalue = <STDIN> );

53

52 }51 return;

50  print( "Invalid value.\n" );

49 else {

48 }

47  print( "Enter the employee's new social security number: ");

46 $field = "SocialSecurity";

45 elsif ( $change == 5 ) {

44 }

43  print( "Enter the employee's new year of birth: " );

42 $field = "YearBorn";

41 elsif ( $change == 4 ) {

40 }

39  print( "Enter the employee's new Last name: " );

38 $field = "LastName";

37 elsif ( $change == 3 ) {

Updates the

database the

user desires

67 my @array;66 print( "\n" );

65

64 $sth->execute();

63

62 my $sth = $dbh->prepare( q { SELECT * FROM employee } );

61 # Now print the updated database 

6059 $dbh->do( $query );

58 print( "$query \n" );

Prints the database in its updated

form with the special format

Page 283: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 283/319

fig15_22.pl

81 .

80 $array[ 0 ], $array[ 1 ], $array[ 2 ], $array[ 3 ], $array[ 4 ]

79 @<<<<<<@<<<<<<<<<@<<<<<<<<<<@<<<<<@<<<<<<<<<<<

78 format STDOUT =

77

76 $sth->finish();

75 $dbh->disconnect();

74 warn( $DBI::errstr ) if $DBI::err;

73 # Clean up 

72

71 }

70  write();

69 while ( @array = $sth->fetchrow_array() ) {

68

Enter the Employee ID number of the record you wish to change: 0004

 Which value would you like to change:1. Employee Identification.2. First name.3. Last name.4. Year of Birth.5. Social Security Number.? 2Enter the employee's new First name: MichelleUPDATE employee SET FirstName = 'Michelle' WHERE EmployeeID =

'0004'

Page 284: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 284/319

fig15_22.pl 

Program Output

0004 Michelle Black 1965 222-44-88880001 Jim Blue 1943 999-85-36980002 Kate Green 1977 111-21-74540003 Wendy White 1959 000-84-3196

DBI and the Web

• Interfaces

Same as when making any other CGI script

Page 285: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 285/319

 – Same as when making any other CGI script

 – No special issues when dealing with the web

109 use CGI qw( :standard );

8 use DBD::ODBC;

7 use DBI;

6 use strict;

5 use warnings;

4

3 # Demonstrates providing a web interface for a database. 2 # Fig. 15.21: fig15_23.pl 

1 #!perl 

Page 286: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 286/319

fig15_23.pl

29 }

28 end_form();

27 submit( -value => "Click to Proceed" ),

26  br(), br(), br(), br(), br(),

25 hidden( { -name => "LAST", -value => "MAIN" } ),

24 'Update a Record' ] ),

23 'Delete a Record',

22 'Insert a Record',

21 -value => [ 'View the Database',

20  popup_menu( -name => 'selection',

19 start_form(),

18  print h1( "Database Manager" ),

17 unless ( param ) {16

15  background=>"http://localhost/images/background.jpg" });

14 start_html( { title => "Working with DBI",

13 print header(),

12

11 my $DSN = "dbi:ODBC:employeeDB";

Creates a new form

with the dropdown list

to choose an action to

perform on the table

Sets the background

40 }

39 displayUpdate($dbh) if ($selection eq "Update a Record");

38 displayDelete($dbh) if ($selection eq "Delete a Record");

37 displayInsert() if ( $selection eq "Insert a Record" );

36 view( $dbh ) if ( $selection eq "View the Database" );

35

34 my $selection = param( "selection" );

33 if ( param( "LAST" ) eq "MAIN" ) {

3231 my $dbh = DBI->connect( $DSN, "", "", { RaiseError => 1 } );

30 else {

Connects to the database

or else generates an error

Page 287: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 287/319

fig15_23.pl

60

59 print end_html();

58

57 }

56 $dbh->disconnect();

55 }54 view( $dbh );

53 updateRecord( $dbh );

52 elsif ( param( "LAST" ) eq "UPDATE2" ) {

51 }

50 updateRecordForm( $dbh );

49 elsif ( param( "LAST" ) eq "UPDATE1" ) {

48 }

47 view( $dbh );46 deleteRecord( $dbh );

45 elsif ( param( "LAST" ) eq "DELETE" ) {

44 }

43 view( $dbh );

42 insertRecord( $dbh );

41 elsif ( param( "LAST" ) eq "INSERT" ) {

40 }

Executed the code based on

the choice made by the user

71

70 $sth->finish();

69 my $rows = $sth->fetchall_arrayref();

68

67 $sth->execute();

66 "SELECT * FROM employee ORDER BY EmployeeID ASC" );

65 my $sth = $dbh->prepare(

64

63 my $dbh = shift();62 {

61 sub view

Orders all the employees

by their ID number

Create a table to display all

Page 288: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 288/319

fig15_23.pl

90

89 }

88 "Back to the Main Database Page" );

87 a( { -href => "/cgi-bin/fig15_23.pl" },

86 " records.",br(), br(),

85 "Your query yielded ", b( scalar( @$rows ) ),

84  br(), br(),

83 -cellspacing => 0 }, $tablerows ),

82 table( { -border => 0, -cellpadding => 5,

81  print h1( "Employee Database" ),

80

79 }

78 $tablerows .= Tr( td( { -bgcolor => "#dddddd" }, $row ));77 foreach my $row ( @$rows ) {

76

75 th( { -bgcolor => "#dddddd" }, [ "YOB", "SSN" ] ) );

74 [ "ID", "First", "Last"] ),

73 Tr( th( { -bgcolor => "#dddddd", -align=>'left' },

72 my $tablerows =

71 Create a table to display all

of the database information

A page that will display

the database results

100 textfield( -name => 'LASTNAME' ), br(),99 "Last Name", br(),

98 textfield( -name => 'FIRST' ), br(),

97 "First Name", br(),

96 textfield( -name => 'ID' ), br(),

95 "Employee ID", br(),

94 start_form(),

93  print h3( "Add a new employee to the database." ), br(),92 {

91 sub displayInsert

A group of fields to be

filled in to add the new

employee to the database

Page 289: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 289/319

fig15_23.pl

119

118 "SELECT EmployeeID, FirstName, LastName FROM employee ");

117 my $sth = $dbh->prepare(

116

115 my $dbh = shift();

114{

113 sub displayDelete

112

111}

110 "Back to the Main Database Page" );

109 a( { -href => "/cgi-bin/fig15_23.pl" },

108 end_form(), br(), br(),

107  br(), br(), submit( -value => "Add New Employee" ),

106 -override => "1" } ),

105 hidden( { -name => "LAST", -value => "INSERT",

104 textfield( -name => 'SSN' ),

103 "Social Security Number", br(),

102 textfield( -name => 'YEAR' ), br(),

101 "Year of Birth", br,

129 $sth->finish;

128

127 }

126 $names{ $row[ 0 ] } = join( " ", @row[ 1, 2 ] );

125  push( @ids, $row[ 0 ] );

124 while ( my @row = $sth->fetchrow_array ) {

123

122 my ( %names, @ids );

121

120 $sth->execute();

Generates a list of the

employees in the

database to be removed

Page 290: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 290/319

fig15_23.pl

146

145}

144 "Back to the Main Database Page" );

143  br(), br(), a( { -href => "/cgi-bin/fig15_23.pl" },

142 "This action removes the record permanently." ),141 font( { -color => "red" },

140 end_form(),

139 submit( -value => "Delete a Record" ), br(), br(),

138 -override => 1 } ),

137 hidden( { -name => "LAST", -value => "DELETE",

136 -labels => \%names ), br(), br(), br(),

135 -value => \@ids,

134  popup_menu( -name => 'DELETE_ID',

133 "Select an Employee to delete ",

132 start_form(),

131  print h3( "Delete an employee from the database" ), br(),

130

129 $sth->finish;

Passes the employee to

be deleted

Uses the list to create a

dropdown list with employee

names to be deleted

$

157156 my ( %names, @ids );

155

154 $sth->execute();

153

152 "SELECT EmployeeID, FirstName, LastName FROM employee ");

151 my $sth = $dbh->prepare(

150

149 my $dbh = shift();148{

147 sub displayUpdate

Create the table to display

the updated information

Page 291: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 291/319

fig15_23.pl

178

177}

176 "Back to the Main Database Page" );

175 a( { -href => "/cgi-bin/fig15_23.pl" },

174 end_form(),

173 submit( -value => "Update a Record" ), br(), br(),172 -override => 1 } ),

171 hidden( { -name => "LAST", -value => "UPDATE1",

170 -labels => \%names ), br(), br(), br(),

169 -value => \@ids,

168  popup_menu( -name => 'UPDATE_ID',

167 "Select an Employee to update ",

166 start_form(),

165  print h3( "Update an employee in the database" ), br(),164

163 $sth->finish;

162

161 }

160 $names{ $row[ 0 ] } = join( " ", @row[ 1, 2 ] );

159  push( @ids, $row[ 0 ] );

158 while ( my @row = $sth->fetchrow_array ) {

Passes the employee to

have fields changed

Generates a list of the users

in the database for updating

188

187 $sth->execute();

186

185 my $sth = $dbh->prepare( $statement );

184  param( 'UPDATE_ID' ) . "'";

183 "WHERE EmployeeID = '" .

182 my $statement = "SELECT * FROM employee " .

181 my $dbh = shift();180{

179 sub updateRecordForm 

Gets the desired

employees information

Page 292: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 292/319

fig15_23.pl

205

204 }

203 -override => 1 ), br();

202 textfield( -name=>$_, -value => $values[ $_ ],

201  print $names[$_], br(),200 foreach ( 1 .. 4 ) {

199

198 hidden( { -name => '0', -value => $values[ 0 ] } );

197 "@values\n", br(),

196 start_form(),

195  br(), br(),

194  print h3("Updating the record for employee #$values[ 0 ]."),

193 

192 $sth->finish();

191 "Social Security Number " );

190 my @names = ( "", "First Name ", "Last Name ", "Year Born ",

189 my @values = $sth->fetchrow_array;

188

Passes that

employee to have

the record changed

Displays the

employees

information

216 my $dbh = shift();215{

214 sub insertRecord 

213

212}

211 "Back to the Main Database Page" );

210 a( { -href => "/cgi-bin/fig15_23.pl" },

209 end_form(),

208 -override => 1 } ),207 hidden( { -name => "LAST", -value => "UPDATE2",

206  print submit( -value => "Update the Record" ),

Adds a new record to the database

Page 293: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 293/319

fig15_23.pl

236}

235 " deleted.", br(), br();

234  print "Employee #", param( 'DELETE_ID' ),

233 $dbh->do( $string );

232

231  param( 'DELETE_ID' ) . "'";230 "WHERE EmployeeID = '" .

229 my $string = "DELETE FROM employee ".

228 my $dbh = shift();

227{

226 sub deleteRecord 

225

224}

223 $dbh->do( $string );

222

221 ( '$id', '$first', '$last', '$year', '$ssn' );";

220 my $string = "INSERT INTO employee VALUES

219  param( 'YEAR' ), param( 'SSN' ) );

218 ( param( 'ID' ), param( 'FIRST' ), param( 'LASTNAME' ),

217 my ( $id, $first, $last, $year, $ssn ) =

Removes a specified

record from the database

246 "SocialSecurity = '$ssn' " .245 "LastName = '$last', YearBorn = '$year', " .

244 my $string = "UPDATE employee SET FirstName = '$first', " .

243  param( '3' ), param( '4' ) );

242 ( param( '0' ), param( '1' ), param( '2' ),

241 my ( $id, $first, $last, $year, $ssn ) =

240 my $dbh = shift();

239{

238 sub updateRecord 

Page 294: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 294/319

fig15_23.pl

250}

249 $dbh->do( $string );

248

247 "WHERE EmployeeID = '$id'"; Updates the correct record

from the database with the

user entered information

Page 295: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 295/319

fig15_23.pl 

Program Output

Page 296: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 296/319

fig15_23.pl 

Program Output

Page 297: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 297/319

fig15_23.pl 

Program Output

Page 298: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 298/319

fig15_23.pl 

Program Output

Page 299: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 299/319

fig15_23.pl 

Program Output

Page 300: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 300/319

fig15_23.pl 

Program Output

Page 301: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 301/319

fig15_23.pl 

Program Output

DBL Utility Functions

• Utility functions

 – Allows a user to determine the database

Page 302: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 302/319

support provided by the computer that theuser is using

 – The available_drivers function• Returns the available database drivers installed

 – The data_sources function

• Returns the available databases registered to thesystem

MySQL Server

• MySQL

 – Multi-platform database

Page 303: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 303/319

p

 – Multi0user database

 – Multithreaded database

 – Open source software

12

11 { RaiseError => 1 } );10 my $dbh = DBI->connect( "DBI:mysql:USERDB", "root", "",

9

8 use DBD::mysql;

7 use DBI;

6 use strict;

5 use warnings;

4

3 # Creating a table. 2 # Fig. 15.24: fig15_24.pl 

1 #!/usr/bin/perl 

Loads the MySQL driver

Page 304: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 304/319

fig15_24.pl

31 Rating INT )";

30 Hours INT,

29 'Other' ),

28 'Linux',

27 'Macintosh',

26 'Windows 98',

25 OpSys ENUM( 'Windows NT',

24 'Antarctica' ),

23 'Australia',

22 'Africa',

21 'Asia',

20 'Europe',

19 'South America',

18 Continent ENUM( 'North America',

17 Phone VARCHAR( 30 ),

16 Email VARCHAR( 30 ),

15 LastName VARCHAR( 30 ),

14 FirstName VARCHAR( 30 ),

13 my $string = "CREATE TABLE Users (

12

 VARCHAR is used to

tell the program that

it is creating variablelength textboxes

Creates an SQL table

40 'Windows 98', 3, 4 )" );

39 '(555)555-5555', 'North America',

38  VALUES ( 'John', 'Doe', 'john\@doe.net',

37 Continent, OpSys, Hours, Rating )

36 FirstName, LastName, Email, Phone,

35 $dbh->do( "INSERT INTO Users (

34

33 $dbh->do( $string );

32

Executes the SQL statement

Inserts one record

into the database

Page 305: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 305/319

fig15_24.pl

John Doe [email protected] (555)555-5555 North America Windows 98 3 4

51 $sth->finish();

50 $dbh->disconnect();

49 warn( $DBI::errstr ) if ( $DBI::err );

48

47 }

46  print( "@row\n" );

45 while ( my @row = $sth->fetchrow_array() ) {

44

43 $sth->execute();

42 my $sth = $dbh->prepare( "SELECT * FROM Users" );

41

12 h1( "Registration Form" ) );

11 print( header(), start_html( "Registration Form" ),10

9 use CGI qw( :standard );

8 use DBD::mysql;

7 use DBI;

6 use strict;

5 use warnings;

4

3 # Using a MySQL database 2 # Fig. 15.25: fig15_25.pl 

1 #!/usr/bin/perl 

Page 306: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 306/319

fig15_25.pl

31 }

30 registrationForm();

29 "in the correct format.", br() );

28  print( "Please enter your phone number ",

27 if ( $phone !~ / \( \d{3} \) \d{3} - \d{4} /x ) {

26

25 my $value = param( "RATING" );

24 my $time = param( "HOURS" );

23 my $os = param( "OS" );

22 my $land = param( "CONTINENT" );

21 my $phone = param( "PHONE" );

20 my $email = param( "EMAIL" );

19 my $last = param( "LAST" );18 my $first = param( "FIRST" );

17 elsif ( !param( "Yes" ) ) {

16 }

15 registrationForm();

14 if ( param( "No" ) || !param ) {

13

12 h1( Registration Form ) );

Creates a list of variables that hold

all the user entered data and asksthe user if the information is correct

Checks the format of the

phone number entered

2 $

41 "Phone: $phone", br(),40 "E-mail: $email", br(),

39 "Name: $first $last", br(),

38  print( h4( "You entered", br(),

37 else {

36 }

35 registrationForm();

34 "between 0 and 24", br() );33  print( "Please enter an integer for hours that is ",

32 elsif ( ( $time !~ / \d+ /x ) || $time < 0 || $time > 24 ) {

Checks to format of the

hours the product was used

Page 307: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 307/319

fig15_25.pl

57 }

56 }

55 end_form() );

54 submit( -name => "Yes" ), submit( -name => "No" ),53 "Is this information correct? ", br(),

52

51 hidden( -name => "HOURS" ), hidden( -name => "RATING" ),

50 hidden( -name => "CONTINENT" ), hidden( -name => "OS" ),

49 hidden( -name => "EMAIL" ), hidden( -name => "PHONE" ),

48 hidden( -name => "FIRST" ), hidden( -name => "LAST" ),

47 start_form(),

46

45 "Rating of product: $value:" ), br(),

44 "Hours using product: $time", br(),

43 "OS: $os", br(),

42 "Continent: $land", br(),

Passes the information

to the next form

69 my $dbh = DBI->connect( "DBI:mysql:USERDB", "root", "",

68 if ( $phone =~ / \( \d{3} \) \d{3} - \d{4} /x ) {67

66 my $value = param( "RATING" );

65 my $time = param( "HOURS" );

64 my $os = param( "OS" );

63 my $land = param( "CONTINENT" );

62 my $phone = param( "PHONE" );

61 my $email = param( "EMAIL" );

60 my $last = param( "LAST" );59 my $first = param( "FIRST" );

58 else {

Sets the variables equal

to the user entered data

Opens the database

Page 308: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 308/319

fig15_25.pl

89 }

88 $land, $os, $time, $value ] ) ) ) );

87 [ "$first $last", $email, $phone,

86 Tr( td( { -align => "center" },

85 "Rating" ] )),

84 "Continent", "OS", "Hours",83 Tr( th( [ "Name", "E-mail", "Phone Number",

82 table( { -border => 3, -cellspacing => 3 },

81  br(), br(),

80 "The following information has been recorded:",

79 "registration form $first", br(),

78  print( "Thank you for completing the ",

77

76 $dbh->do( $statement );75

74 '$land', '$os', '$time', '$value' )";

73 ( '$first', '$last', '$email', '$phone',

72 my $statement = "INSERT INTO Users VALUES

71

70 { RaiseError => 1 } );

Inserts the information

into the database

100  print(

99 sub registrationForm {

98

97 print end_html();

96

95 }

94 }

93 registration_form();

92 " correct format.", br() );91  print( "Please enter your phone number in the ",

90 else {

Has the user fill in several

fields of which will be

entered into the database

Page 309: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 309/319

fig15_25.pl

118

117 "Must be of the form (555)555-5555" ) ) ),

116 textfield( -name => "PHONE", -size => 20 ), br(),

115 td( strong( "Phone Number" ), br(),

114113 textfield( -name => "EMAIL", -size => 25 ) ),

112 td( strong( "E-mail Address:" ), br(),

111 Tr( { -valign => "top" },

110

109 textfield( -name => "LAST", -size => 15 ) ) ),

108 td( strong( "Last Name:" ), br(),

107

106 textfield( -name => "FIRST", -size => 15 ) ),

105 td( { -width => '300' }, strong( "First Name:"), br(),

104 Tr( { -valign => "top" },

103 table( { -cellpadding => "3" },

102 start_form(),

101 h3( "Please fill in all fields and then click Proceed."),

129 br()

128 "Macintosh", "Linux", "Other" ] ),127 -value => [ "Windows 98", "Windows NT",

126 radio_group( -name => 'OS',

125 h4( "Which Operating System are you currently running?" ),

124  br(),

123 "Africa", "Antarctica" ] ),

122 "Asia", "Europe", "Australia",

121 -value => [ "North America", "South America",120  popup_menu( -name => "CONTINENT",

119 h4( "What Continent do you live on? " ),

Page 310: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 310/319

fig15_25.pl

139}

138 end_form() );

137 submit( "Proceed" ),

136  br(),

135 -value => [ '1', '2', '3', '4', '5' ] ),

134 radio_group( -name => "RATING",

133 h4( "How would you rate our product on a scale of 1 - 5" ),

132

131 textfield( -name => 'HOURS', -size => 3 ) ),

130 h4( "How many hours a day do you use our product? " ,

129  br(),

Page 311: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 311/319

fig15_25.pl 

Program Output

Page 312: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 312/319

fig15_25.pl 

Program Output

Page 313: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 313/319

fig15_25.pl 

Program Output

12 { RaiseError => 1 } );

11 my $dbh = DBI->connect( "DBI:mysql:USERDB", "root", "",

10

9 use CGI qw( :standard );

8 use DBD::mysql;

7 use DBI;

6 use strict;

5 use warnings;

4

3 # Makes a webpage of statistics from the database. 2 # Fig. 15.26: fig15_26.pl 

1 #!/usr/bin/perl 

Connect to the database

Page 314: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 314/319

fig15_26.pl

30

29 }

28 $rating += $row->[ 3 ];

27 $hours += $row->[ 2 ];

26 $op{ $row->[ 1 ] }++;25 $lands{ $row->[ 0 ] }++;

24 foreach  my $row ( @$results ) {

23

22 my ( $rating, $hours, %lands, %op );

21

20 my $total = scalar( @$results );

19

18 my $results = $sth->fetchall_arrayref();17

16 $sth->execute();

15 FROM Users" );

14 my $sth = $dbh->prepare("SELECT Continent, OpSys, Hours, Rating

13

12 { RaiseError => 1 } );

Extracts the data using thefetchall_arrayref

Totals the user inputhours and ratings

42 th( { width => "50" }, "Total Users" ),

41 my $landrows = Tr( th( { width => "100" }, "Continent" ),40

39 %.2f out 5.", $total, $hours, $rating;

38 hours using your product. They rate it an average of

37 printf"You have a total of %d users spending an average of %.2f

36

35 h1( "User Statistics" );

34 print header, start_html( "User Stats" ),

3332 $rating /= $total;

31 $hours /= $total;Obtains an average

Page 315: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 315/319

fig15_26.pl

61

60 th( "Percent Of Users" ) );

59 th( { width => "50" }, "Total Users" ),

58 my $oprows = Tr( th( { width => "100" }, "Operating System" ),

57

56 table( { -border => 1, -width => "100%" }, $landrows );

55 print h3( { -align => "center" }, "Users by Continent" ),

54

53 }

52 ) );

51 td( br ) ) )

50 -bgcolor=>"#0000FF" }, br ),

49 Tr( td( { -width => "$percent%",48 td( table( { -width => "100%" },

47 $landrows .= Tr( td( $_ ), td( $lands{ $_ } ),

46 my $percent = int( $lands{ $_ } * 100 / $total );

45 foreach ( sort { $lands{ $b }<=>$lands{ $a }} keys( %lands )) {

44

43 th( "Percent Of Users" ) );

Creates an HTML table

to display the results

Creates a bar graph

to display the data

71

70 }69 ) ) ) );

68 td( br )

67 -bgcolor => "#0000FF" }, br ),

66 Tr( td( { -width => "$percent%",

65 td( table( { -width => "100%" },

64 $oprows .= Tr( td( $_ ), td( $op{ $_ } ),63 my $percent = int( $op{ $_ } * 100 / $total );

62 foreach ( sort { $op{ $b } <=> $op{ $a } } keys( %op ) ) {

Creates the same table

only for the OS stats

Page 316: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 316/319

fig15_26.pl75 $dbh->disconnect();

74

73 table( { -border => 1, -width => "100%" }, $oprows );

72 print h3( { -align => "center" }, "Operating System statistics" ),

71

Page 317: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 317/319

fig15_26.pl 

Program Output

Page 318: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 318/319

fig15_26.pl 

Program Output

Thanks!

Page 319: Complete Perl Tutorial

8/2/2019 Complete Perl Tutorial

http://slidepdf.com/reader/full/complete-perl-tutorial 319/319

Questions?