Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl...

48
Chapter 9 The Basics of Perl
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    225
  • download

    0

Transcript of Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl...

Page 1: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

Chapter 9The Basics of Perl

Page 2: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-2

For perl using CGI module you may need: ppm install CGI

• C:\PERL> ppm install CGI• ====================• Install 'CGI' version 2.91 in ActivePerl 5.8.7.815.• ====================• Installing C:\Perl\html\site\lib\CGI.html• Installing C:\Perl\html\site\lib\CGI\Apache.html• Installing C:\Perl\html\site\lib\CGI\Carp.html• Installing C:\Perl\html\site\lib\CGI\Cookie.html• Installing C:\Perl\html\site\lib\CGI\Fast.html• Installing C:\Perl\html\site\lib\CGI\Pretty.html• Installing C:\Perl\html\site\lib\CGI\Push.html• Installing C:\Perl\html\site\lib\CGI\Switch.html• Installing C:\Perl\html\site\lib\CGI\Util.html• Installing C:\Perl\site\lib\CGI.pm• Installing C:\Perl\site\lib\CGI\Apache.pm• Installing C:\Perl\site\lib\CGI\Carp.pm• Installing C:\Perl\site\lib\CGI\Cookie.pm• Installing C:\Perl\site\lib\CGI\Fast.pm• Installing C:\Perl\site\lib\CGI\Pretty.pm• Installing C:\Perl\site\lib\CGI\Push.pm• Installing C:\Perl\site\lib\CGI\Switch.pm• Installing C:\Perl\site\lib\CGI\Util.pm• Successfully installed CGI version 2.91 in ActivePerl 5.8.7.815.

Page 3: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-3

Running CGI…an html points to a cgi program

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<!-- reply.html A trivial document to call a simple Perl CGI program --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> XHTML to call the Perl CGI program, reply.cgi </title> </head> <body> <p> This is our first Perl CGI example <br /><br /> <a href = "http://localhost/cgi-bin/reply.cgi"> Click here to run the CGI program, reply.cgi </a> </p> </body></html>

Page 4: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-4

9.2 Scalars and Their Operations (continued)

- Scalar type is specified by preceding the name with a $

- A name must begin with a letter; any number of letters, digits, or underscore characters can follow - Names are case sensitive (by convention, names of variables use only lowercase letters)

- Names embedded in double-quoted string literals are interpolated

e.g., If the value of $salary is 47500, the value of "Jack makes $salary dollars per year" is "Jack makes 47500 dollars per year"

- Variables are implicitly declared

- A scalar variable that has not been assigned a value has the value undef (numeric value is 0; string value is the null string)

- Perl has many implicit variables, the most common of which is $_

Page 5: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-5

9.2 Scalars and Their Operations (continued) - Numeric Operators - Like those of C, Java, etc.

Operator Associativity++, -- nonassociativeunary - right** right*, /, % leftbinary +, - left

- String Operators - Catenation - denoted by a period

e.g., If the value of $dessert is "apple", the value of $dessert . " pie" is "apple pie"

- Repetition - denoted by x

e.g., If the value of $greeting is "hello ", the value of $greeting x 3 is "hello hello hello "

Page 6: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-6

9.3 Assignment Statements and Simple Input and Output (continued)

- Screen Output

print one or more string literals, separated by commas

e.g., print "The answer is $result \n";

- Example program:

print "Please input the circle’s radius: "; $radius = <STDIN>; $area = 3.14159265 * $radius * $radius; print "The area is: $area \n";

- One way to run a Perl program:

perl –w prog1.pl

- Two useful flags: -c means compile only (for error checking) -w means produce warnings for suspicious stuff (you should always use this!)

- To get input from a file (read with <>): perl –w prog1.pl prog1.dat

Page 7: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-7

Running perl programs in perl\bin

You may wish to create a DOS shortcut to Perl.

Do this by right clicking on the desktop and selecting “create shortcut” for

Command.com.

Once created you can edit the shortcut to open in the appropriate directory.

You can add perl.exe to the tools/preferences in textpad and run perl from there. (I haven’t done this).

Note- you might not be able to do any of this in the lab

You’ll have all the usual issues with path settings

Page 8: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-8

Running perl programs in perl\bin

C:\PERL\BIN>perl example.pl

Please input the circleÆs radius: 4

The area is: 50.2654824

C:\PERL\BIN>perl hello.pl

hello world

Page 9: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-9

Some perl program examples

• Perl programs will need their first line to include the path to the perl compiler. This line starts with #! (called shebang)

#!c:\perl\bin\perl.exe

Perl statements end in a semi-colon

Page 10: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-10

Hello world script: note shebang 1st line points to perl on system

#!c:\perl\bin\perl.exe

print "Content-type:text/html\n\n";

print "hello world";

Page 11: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-11

Deploying the helloworld example:Drop perlscripts into cgi-bin

Page 12: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-12

Using variables

• Simple variables in perl start with a $:

$mystring = "Hello, World";

$mypi = "3.14159";

Note, there is no difference between string, int and float value declaration or assignments.

Page 13: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-13

Using variables

#!c:\perl\bin\perl.exeprint "Content-type: text/html \n\n"; # the header$mystring = "Hello, World";$myescapechar = "Welcome to Joe\'s";$myinteger = "5";$myinteger2 = "-5";$mypi = "3.14159";print $mystring; print "<br />"; print $myescapechar; print "<br />"; print $myinteger; print "<br />"; print $myinteger2; print "<br />"; print $mypi;

Page 14: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-14

Vars.pl

Page 15: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-15

Shortcut operators as in java or c++

#!c:\perl\bin\perl.exe

print "content-type: text/html \n\n"; #The header

$x = 14;

$y = 10;

$area = ($x * $y);

print $area;

print "<br />";

$x += 4; #adds 4 to x

$y += 12; #adds 12 to y

$area = ($x * $y);

print $area;

Page 16: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-16

Running vars2

Page 17: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-17

Strings

#!c:\perl\bin\perl.exeprint "content-type: text/html \n\n"; #The header$single = "This string is single quoted";$double = 'This string is double quoted';$userdefined = q^Carrot is now our quote^;print $single; print " "; print $double; print " "; print $userdefined;

Page 18: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-18

Running it

Page 19: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-19

substrings

#!c:\perl\bin\perl.exe

print "content-type: text/html \n\n"; #The header

$mystring = "Welcome to higgins perl examples!";

$twoarguments = substr($mystring, 11);

$threearguments = substr($mystring, 8, 2);

print $twoarguments;

print "<br />";

print $threearguments;

Page 20: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-20

More substrings

#!c:\perl\bin\perl.exe

print "content-type: text/html \n\n"; #The header

$mystring = "Welcome to www.anywhere.com!";

print $mystring;

print "";

substr($mystring, 11) = "www.google.com!";

print $mystring;

Page 21: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-21

9.10 File Input and Output

- The open function is used to create the connection between a filehandle and the external name of a file; it also specifies the file’s use

- A file’s use is specified by attaching < (input), > (output, starting at the beginning of the file), or >> (output, starting at the end of the existing file) to the beginning of its name

open (INDAT, "<prices"); open (OUTDAT, ">averages");

- Because open can fail, it is usually used with die

open (OUTDAT, ">>salaries") or die "Error - unable to open salaries $!";

- One line of output to a file:

print OUTDAT "The answer is: $result \n";

- One line of input from a file:

$next = <INDAT>;

- Buffers (of any size) of input can be read from a file with the read function

SHOW wages.pl

Page 22: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-22

Remarks on scalars

• As in the Unix shell, you can use different quoting mechanisms to make different kinds of values. Double quotation marks (double quotes) do variable interpolation and backslash interpolation (such as turning \n into a newline) while single quotes suppress interpolation. And backquotes (the ones leaning to the left) will execute an external program and return the output of the program, so you can capture it as a single string containing all the lines of output.

Page 23: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-23

Scalar assignment examples

• $answer = 42; # an integer

• $pi = 3.14159265; # a "real" number

• $avocados = 6.02e23; # scientific notation

• $pet = "Camel"; # string

• $sign = "I love my $pet"; # string with interpolation

• $cost = 'It costs $100'; # string without interpolation

• $thence = $whence; # another variable's value

• $salsa = $moles * $avocados; # a gastrochemical expression

• $exit = system("vi $file"); # numeric status of a command

• $cwd = `pwd`; # string output from a command

Page 24: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-24

Scalar assignment examples

And while we haven't covered fancy values yet, we should point out that scalars may also hold references to other data structures, including subroutines and objects.

$ary = \@myarray; # reference to a named array

$hsh = \%myhash; # reference to a named hash

$sub = \&mysub; # reference to a named subroutine

$ary = [1,2,3,4,5]; # reference to an unnamed array

$hsh = {Na => 19, Cl => 35};

# reference to an unnamed hash

$sub = sub { print $state };

# reference to an unnamed subroutine

$fido = new Camel "Amelia"; # reference to an object

Page 25: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-25

Practice writing perl: quadratic equation

print "Please input the value of a ";$a = <STDIN>;print "Please input the value of b ";$b = <STDIN>;print "Please input the value of c ";$c = <STDIN>;# Compute and display the result$disc=$b*$b-4*$a*$c;$denom=2*$a;if($disc>0){$r1=(-$b-sqrt($disc))/$denom;$r2=(-$b+sqrt($disc))/$denom;print "two real roots are: $r1 and $r2 \n";}elsif(!$disc){ #zero discriminant means double real root$result=-$b/$denom;print "Double real root is: $result \n";}else{$real_part=-$b/$denom;$complex_part=sqrt(-$disc)/$denom;print "Two complex roots \n";print "$real_part +$complex_parti \n";print "$real_part -$complex_parti \n";}

Page 26: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-26

quadratic equation

if($disc>0){$r1=(-$b-sqrt($disc))/$denom;$r2=(-$b+sqrt($disc))/$denom;print "two real roots are: $r1 and $r2 \n";}elsif(!$disc){$result=-$b/$denom;print "Double real root is: $result \n";}else{$real_part=-$b/$denom;$complex_part=sqrt(-$disc)/$denom;print "Two complex roots \n";print "$real_part +$complex_parti \n";print "$real_part -$complex_parti \n";}

Page 27: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-27

The runs of quadratic.pl

C:\PERL\BIN>perl quadratic.pl

Please input the value of a 1

Please input the value of b 4

Please input the value of c 1

two real roots are: -3.73205080756888 and

-0.267949192431123

C:\PERL\BIN>perl quadratic.pl

Please input the value of a 1

Please input the value of b 4

Please input the value of c 4

Double real root is: -2

C:\PERL\BIN>

Page 28: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-28

fibonacci

print "Some Fibonacci values\n ";$a = 1;$i=1;$b = 1;while($a<1000){print "Fibonacci value#$i=$a\n ";$b=$a+$b;$a=$b-$a;$i++;}

Page 29: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-29

Run fibC:\PERL\BIN>perl fib.plSome Fibonacci values Fibonacci value#1=1 Fibonacci value#2=1 Fibonacci value#3=2 Fibonacci value#4=3 Fibonacci value#5=5 Fibonacci value#6=8 Fibonacci value#7=13 Fibonacci value#8=21 Fibonacci value#9=34 Fibonacci value#10=55 Fibonacci value#11=89 Fibonacci value#12=144 Fibonacci value#13=233 Fibonacci value#14=377 Fibonacci value#15=610 Fibonacci value#16=987

C:\PERL\BIN>

Page 30: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-30

Arrays and Hashes

• Some kinds of variables hold multiple values that are logically tied together. Perl has two types of multivalued variables: arrays and hashes. In many ways, these behave like scalars--they spring into existence with nothing in them when needed, for instance. But they are different from scalars in that, when you assign to them, they supply a list context to the right side of the assignment rather than a scalar context.

• use an array when you want to look something up by number.

• use a hash when you want to look something up by name. The two concepts are complementary. You'll often see people using an array to translate month numbers into month names, and a corresponding hash to translate month names back into month numbers.

• hashes aren't limited to holding only numbers.

Page 31: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-31

Read data from a file, sort it

$index = 0;# read strings to eofwhile($name = <>) {# chomp and uc names and put it in# the names array...#error in text next line: $names should be @names chomp($name); @names[$index++] = uc($name);}# Display the sorted list of namesprint "\nThe sorted list of names is:\n\n\n";foreach $name (sort @names) { print ("$name \n");}print "\nThe original list of names is:\n\n\n";foreach $name (@names) { print ("$name \n");}

Page 32: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-32

The runC:\PERL\BIN>perl ucnames.pl names.txt

The sorted list of names is:

ANN BOLYNBOB WILLIAMSJACK NALLYJANE SEYMOURLISA WENCKMARK BOYLESUE SMITH

The original list of names is:

BOB WILLIAMSSUE SMITHJACK NALLYLISA WENCKMARK BOYLEANN BOLYNJANE SEYMOUR

Page 33: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-33

Shift, unshift, push and pop

• These functions facilitate building a queue or a stack out of an array.

• Shift pulls the first element off an array (dequeue)

• Unshift works like enqueue

• Push and pop are the usual stack functions

Page 34: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-34

Pushnpop.pl

# pushnpop.pl# Input: a line of ints and operators with required blank separators# get a line of input text$x=<STDIN>;# Split the line into words...spaces mandatory!!! @line = split(" ",$x);foreach $op (@line) {print " pushing $op \n"; push(@operands,$op); # print "pushing $op\n";}print " popping loop \n";while( $op=pop (@operands) ){ print "popped $op\n";}

Page 35: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-35

Running pushnpop

C:\PERL\BIN>perl pushnpop.pl10 15 20 25 30 35 40 pushing 10 pushing 15 pushing 20 pushing 25 pushing 30 pushing 35 pushing 40 popping looppopped 40popped 35popped 30popped 25popped 20popped 15popped 10

Page 36: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-36

A stack example: Postfix eval C:\PERL\BIN>perl words.pl10 20 * 50 / 1000 * 100 + 5 - processing 10 processing 20 processing * processing 50 processing / processing 1000 processing * processing 100 processing + processing 5 processing -answer is 4095C:\PERL\BIN>

Page 37: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-37

remarks

• Not a very robust program

• Blanks are required separators

• No error handling except illegal chars are flagged

• Good example of string compares and perl scalar manipulation: Don’t forget, for string comparisons use FORTRAN-type eq, ne and so on.

• Trace print output provided for debugging

Page 38: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-38

Postfix code# postfix.pl# Input: a line of ints and operators with required blank separators# Output: postfix eval$x=<STDIN>;# Split the line into words...spaces mandatory!!! @line = split(" ",$x);

foreach $op (@line) {print " processing $op \n"; if ($op ne "+" && $op ne "-" && $op ne "/" && $op ne "*") { push(@operands,$op); # print "pushing $op\n"; } elsif($op eq "-") { $right=pop(@operands); $left=pop(@operands); $val=$left-$right; push(@operands,$val);# print "in minus pushing $val\n";

Page 39: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-39

The rest is the same…last value on stack is the answer

} elsif($op eq "+") { $right=pop(@operands); $left=pop(@operands); $val=$left+$right; push(@operands,$val); # print "in plus pushing $val\n"; } elsif($op eq "*") { $right=pop(@operands); $left=pop(@operands);$val=$left*$right; push(@operands,$val); #print "im mult pushing $val\n"; } elsif($op eq "/") { $right=pop(@operands); $left=pop(@operands); $val=$left/$right; push(@operands,$val); #print "in div pushing $val\n"; } else {print "error";} } #loop ends $ans=shift(@operands); print "answer is $ans";#error if more than 1 value left on stack

Page 40: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-40

More on arrays

• An array is an ordered list of scalars, accessed by the scalar's position in the list. The list may contain numbers, or strings, or a mixture of both. (It might also contain references to subarrays or subhashes.) To assign a list value to an array, you simply group the values together (with a set of parentheses):

• @home = ("couch", "chair", "table", "stove"); • Conversely, if you use @home in a list context, such as on

the right side of a list assignment, you get back out the same list you put in. So you could set four scalar variables from the array like this: ($potato, $lift, $tennis, $pipe) = @home;

• These are called list assignments. They logically happen in parallel, so you can swap two variables by saying:

• ($alpha,$omega) = ($omega,$alpha);

Page 41: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-41

Accessing elements don’t use: @a[i] use: $a[i]

• Since the element you are accessing is a scalar, you always precede it with a $.

• If you want to assign to one array element at a time, you could write the earlier assignment as:

$home[0] = "couch";

$home[1] = "chair";

$home[2] = "table";

$home[3] = "stove";

Page 42: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-42

Two dim array in perl…several ways to do it, here’s one

#two dim arrays in perl

#adjacency lists for a graph

@adjac=([1,2],[0,2,3,5],[0,1,6],[1,4,6],[3,5],[1,4,6,7],[2,3,5,7],[2,5,6]);

for $row ( @adjac ) {

print "@$row\n";

}

Page 43: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-43

Has output

C:\PERL\BIN>perl twod.pl

1 2

0 2 3 5

0 1 6

1 4 6

3 5

1 4 6 7

2 3 5 7

2 5 6

Page 44: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-44

It’s confusing …

• $days=@days is a scalar evaluation of a list. It return the length.

• Closely related to the scalar evaluation of @days is $#days. This will return the subscript of the last element of the array, or one less than the length, since there is (ordinarily) a 0th element.

Page 45: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-45

A queue example

• For a graph G=(V,E) with v in V, the traversal BFS(v) (AKA Breadth-first-search) returns a distance-from-v-ordered traverse of the vertices of the component of G that contains v.

• Starting with v, we list (in natural ordering) all the vertices adjacent to v, then for each of those, in order, all vertices not yet visited, and so on.

• Another way to say it: visit all vertices 1 edge-distance from v, then all vertices a 2-edge distance from v, and so on.

• BFS uses a queue. Enqueue v, then: while queue not empty, remove a vertex, visit it, mark it, and enqueue all adjacent vertices not yet visited.

Page 46: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-46

BFS in perl

C:\PERL\BIN>perl bfs.pladjacency lists:1 20 2 3 50 1 61 4 63 51 4 6 72 3 5 72 5 6 bfs from 4visiting 4visiting 3visiting 5visiting 1visiting 6visiting 7visiting 0visiting 2

Page 47: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-47

Bfs in perl

print "adjacency lists:\n";@adjac=([1,2],[0,2,3,5],[0,1,6],[1,4,6],[3,5],[1,4,6,7],[2,3,5,7],

[2,5,6]); for $row ( @adjac ) { print "@$row\n"; }@visited=(0,0,0,0,1,0,0,0);#all false except 4print " bfs from 4\n";push(@queue,4);while($len=@queue){$next=shift @queue; print "visiting $next\n"; #get vertices from this row for $j ( 0 .. $#{$adjac[$next]} ) { # print "checking $adjac[$next][$j] "; $v=$adjac[$next][$j]; if(!@visited[$v]) {push(@queue,$v); # print "pushing $v "; @visited[$v]=1;} }#for # print "\n"; }#while

Page 48: Chapter 9 The Basics of Perl. © 2006 Pearson Addison-Wesley. All rights reserved. 9-2 For perl using CGI module you may need: ppm install CGI C:\PERL>

© 2006 Pearson Addison-Wesley. All rights reserved. 9-48

Easy to modify so vertex to start from is input

adjacency lists:1 20 2 3 50 1 61 4 63 51 4 6 72 3 5 72 5 6

bfs from 6

visiting 6visiting 2visiting 3visiting 5visiting 7visiting 0visiting 1visiting 4