Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

33
Perl for People Singer XJ Wang Learning Center Available At: http://www.cs.dal.ca/~swang/4173/pfp.ppt

Transcript of Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Page 1: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Perl for People

Singer XJ Wang

Learning Center

Available At: http://www.cs.dal.ca/~swang/4173/pfp.ppt

Page 2: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Perl Variables Perl is a type-less language (no explicit types like integers, strings,

doubles etc) Main data categories (types) are

Scalars Lists Hashes

Variables are automatically created when you first use them; however to be safe you should declare them first; Declaring a variable makes them valid for the block of code they are in Putting the following in the top of the Perl script enforces you to declare

variables use strict; my $scalarVariable; my @listVariable; my %hashVariable;

Page 3: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Scalar Variables Either a number or a string of characters (doesn’t matter) Scalar variables always begin with $ No limitation on size of a scalar variable un-initialized values are set to undef which is either 0 or “”

(empty string) depending on context 0 and “” are both considered false in conditionals All standard operators are provided like

Arithmetic Operations +, -, /, * String Length length( $scalar ) Concatenation $newScalar = $front . $back;

Substitution is allowed for scalars In case below $b would contain the value “hello ted”

$a = “ted”; $b = “hello $a”;

Page 4: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Scalar Variables (con’t) Scalar Contexts:

$a = 5; $b = “4A”;$c = $a + $b; $d = $a . $b;

Numerical Context: $c since addition is number operation, $b is internally converted to a number and added to $a; the result is 9

String Context: $d since . is an string operation; $a is internally converted to a string and appended to $b; the result is “54A”

the value of $a and $b are not changed Comparison Operators:

Numerical Context <, <=, ==, !=, >=, > if ( $a < $b ) …

numerical comparison is made String Context lt, le, eq, ne, ge, gt

if ( $a eq $b )… alphabetical comparison is made

Page 5: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

List Variables Similar to Vectors or Linked Lists

can also be used like a stack and queue Elements are indexed like an array – starting at 0 Each element in the list must be a scalar No fixed size – up to limits of system memory List variables names always begin with @ Any position in list that hasn’t been explicitly defined has the

value undef @ refers to the list as a whole, $ refers to elements

@array = (“elementA”, “elementB”, “elementC”); $array[2] is the 3rd element with value “elementC” $array[5] = “ted”; sets the 6th element in the list to “ted”

Copying is done through assignment (each element is copied) @copy = @original;

Page 6: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

List Variables (con’t) Sorting:

Alphabetically @sorted = sort @unsorted; Numerical @sorted = sort {$a <=> $b} @unsorted;

Reversing: @ reversed = reverse @normal;

Accessing Element: @list; $scalarVariable = $list[4]; $scalarVariable = $list[$index];

Setting Element: @list $list[5] = ‘cat’; $list[$index] = $nameOfPerson; $list[8] = 5;

Getting Number of Elements in a List: $numElements = scalar @list;

Page 7: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

List Variables (con’t) Operation at Head of List (low index):

Insertion unshift @list, $scalar; Deletion --> $scalar = shift @list;

Operation at Tail of List (high index): Insertion push @list, $scalar; Deletion $scalar = pop @list;

Combining Lists and Scalars: @newList = (@listA, $scalar); @newList = ($scalar, @listA);

Combinining Multiple Lists @newList = (@listA, @listB); @newList = (@listB, @listA);

NOTE: does not form multi-dimensional lists, instead creates one list with elements from both parts

Page 8: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Hash Variables A hash table data structure; Like a STL Map in C++, HashMap or

HashSet in Java; Key, Value pairs – both must be scalars No internal order is maintained Keys must be unique; no two element can have the same key

Attempting to insert a second value for the same key, then the first value gets overwritten

Hash variables names always begin with % % refers to hash as a whole, $ refers to elements

%hash; $hash{$key} = $value; $hash{5} = “egg”; $hash{“ted”} = “bacon”;

Page 9: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Hash Variables (con’t) Copying is done through assignment (each element is copied)

%copy = %original; Lists of Keys/Value

List of Keys @keys = keys %hash; List of Values @values = values %hash;

Insertion/Deletion/Access: %hash Insertion $hash{$key} = “value”; Deletion delete $hash{$key}; Access $scalarValue = $hash{$key}

If no value exists for the given key, the value undef is returned Reversing

%reverseHash = reverse %normalHash; Swaps the keys and values If it has two values that are the same, then the result is not deterministic

Page 10: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Hash Variables (con’t) Hash from List

%hash = @list; Every even element becomes key for odd element (the

odd element after the even one) If two even elements (potential keys) are the same, then

the result is not deterministic If the list contains an odd number of elements, the last

element (a potential key) is ignored Hash from List

@list = %hash; Every even element becomes key for odd element (the

odd element after the even one) Order of the elments are not gauarneteed

Page 11: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Control Structures Control structures in Perl are very much like C, C++, Java

with the following exceptions: No switch or case statement else if is written as elsif Additional unless control which works exactly the opposite of the

if control; not used that often curly braces are always required

Wrong Right

if ($a == 5 )

print “hello world”;

else

print “world hello”;

if ($a == 5 ){ print “hello world”;

}

else{

print “world hello”;

}

Page 12: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Control Structures (con’t) foreach control structure:

Goes through list and set the scalar to successive values in the list in order (low index to high)

my $scal;foreach $scal ( @list ){

print “element -> $scal \n”;}

To print all keys and values in a hash my $scal;foreach $scal ( keys %hash ){

print “$scal -> $hash{$scal}\n”;}

To sort all the keys alphabetically use this line instead foreach $scal ( sorted keys %hash ){

Page 13: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Input and Output

Reading from STDIN <STDIN> is variable for standard in Reads one line and assign it to variable $a chomp removes the new line at the end

$a = <STDIN>;

chomp( $a );

Printing to STDOUT/STDERR Use print to send a line to standard out Variables are subisuted when necessary

print “Hello $world\n”;

printf() like C/C++ is also available, but slower then print To print to STDERR: print STDERR “Hello $world\n”;

Page 14: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Input and Output (con’t)

Printing Large Documents the end marker (EOF) must immediately follow the << the second end marker (EOF) must be at the

beginning of the line the semi-colon ; must be on a new line variables are substituted when appropriate

print <<EOF

blah blah $variable

blah blah blah text

EOF

;

Page 15: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Input and Output (con’t) Opening/Closing Files

Reading open(FILE, “file.txt”); Writing open(FILE, “>file.txt”); Appending open(FILE, “>>$file”); Closing close(FILE);

FILE is a file handle, can be any other name Separate from $, %, @ variables

File I/O Read from file: $line = <FILE>; Write to file: print FILE “hello wrold”;

Sample Program: open(FILE, "file.txt"); open(FILE2, ">out.txt");my $line;while( $line = <FILE> ){

print FILE2 $line;}close(FILE); close(FILE2);

Page 16: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Warn and Die

Warn and Die can be used to convey error messages when statement fails to execute properly warn prints error message and continues execution die print error messages and halts execution

the predefined variable $! contains the error message the system provides

Syntax:open(FILE, “in.txt”) || die “not found: $!\n”;

open(FILE, “in2.txt”) || warn “not found $!\n”;

Page 17: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Subroutines Subroutines are like functions/procedures in C/C++/Java Subroutines are identified only by the name when called, the

arguments do not matter by default Passing of parameters to subroutines are done by copying (like

C) All parameters to a subroutine are put into a special list @_

when parsing arguments in the subroutine the list or hash will grab all remaining elements in the list @_, thus only one list or hash can be passed in as arguments – the last argument

except when using References (later) Return value from a subroutine can be a scalar or an list/hash

Page 18: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Subroutines (con’t)sub sample1{ # @l1 grabs all remaining arguments, @l2 empty

my ($var1, $var2, @l1, @l2) = @_;…..

}sub sample2{ # @rest grabs rest of arguments if any

my ($var1, $var2, @rest) = @_;…..

}my @list1 = (“a”, “b”, “c”);my @list2 = (“c”, “d”, “e”);my $v1 = “alpha”; my $v2 = “beta”;sample1($v1, $v2, @list1, @list2); # 1sample1($v1, $v2, @list1); # 2sample2($v1, $v2, @list1, @list2); # 3sample2($v1, $v2, @list1); # 4

• the first list that is part of the argument list in the subroutine takes all remaining arguments; the second list is empty

Page 19: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

References References are like pointers in C/C++ the operator \ gives you reference to a variable, the reference

itsself is a scalar $scalarRef = \$scalar; $listRef = \@list; $hashRef = \%hash;

Accessing the Variable being References Scalar $$scalarRef List $listRef->[$index] Hash $hashRef->{$key};

References provides way to pass multiple lists/hashes into an subroutines a way for subroutines to change a list/hash passed into it

Page 20: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

References (con’t)

sub changeL{my $listRef = $_[0];$listRef->[0] = “ABA”;

}my @list = (“BAB”);my $listR = \@list;print “$list[0]\n”;changeL($listR);print “$list[0]\n”; Results when Run

BABABA

Page 21: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Sample Program#!/usr/bin/perl -w## this is a commentuse strict;

sub printHello{ my ($name, $number) =@_;

print "Hello $name, welcome to World!\n"; return ($number*2, $number+4);}

print "Enter Your Name: ";my $nA = <STDIN>;chomp($nA);print "Enter Your Age: ";my $nB = <STDIN>;chomp($nB);my ($returnA, $returnB) = printHello($nA, $nB);print "$returnA is first and $returnB is second\n";

Page 22: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

CGI - Scripts Made Easier

Perl Modules for CGI and Web Pages Helps with the following

Setting context types Accessing and parsing values submitted by forms Setting and retrieving cookies generate forms and HTML Pages setting and retrieving session data

Two ways of accessing it Traditional functions Object Oriented style

Page 23: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

CGI (con’t) Running Perl-CGI on Borg/Torch/Locutus:

ensure that your web page is accessible and has correct permissions http://help.cs.dal.ca/faq/tutorials/web_sites/basic_site.php

Setup the scripts as following: http://help.cs.dal.ca/faq/tutorials/web_sites/cgi_script.php

1. First you will need to create a cgi-bin bin directory in your public_html directory: mkdir ~/public_html/cgi-bin

2. Next you must grant world read and execute permissions on your cgi-bin directory: chmod a+rx ~/public_html/cgi-bin or chmod 755 ~/public_html/cgi-bin

3. Next you must place your CGI scripts in the cgi-bin directory and grant world execute permissions on each script: chomd a+x script.cgi or chmod 711 script.cgi

4. Your scripts can now be referenced at http://www.cs.dal.ca/~username/cgi-bin/script.cgi

Page 24: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

CGI (con’t)

Must include the CGI module in the scriptuse CGI qw/:standard/;

Printing the context type for the browserprint header();

outputs something like Content-Type: text/html; To call a Perl-CGI script from a form

set the script as the action of the form GET or POST does not matter

ensure that each form element has a unique name for check boxes, choice boxes, selects give each option an

unique value

Page 25: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

CGI (con’t)

<form method=“GET” action=“sample.cgi”><input type="text" name="name" size="12"><input value="Submit Form!"><input type="reset" value="Clear Form!">

to get the value in the form element, simply call the param function with the element name as argument the return type depends on the form element, ones that

allow multiple choices return a list Notes

calls for check boxes return “checked” or undef radio buttons return the value of the one chosen

$value = param(“name”);@values = param(“other”);

Page 26: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

DBI - Database Interface Database Independent Driver for Perl

Can talk to any major database like MySQL Oracle DB2 Microsoft SQL Server PostgreSQL

You can create your tables through DBI but for convince you typically want to do it through SQL*Plus (Oracle)

Include the module DBI in the script use DBI; Major Objects:

$dbh database handle $sth statement handle

Page 27: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

DBI (con’t) Connecting to DB (Oracle) and Disconnecting

$ENV{'ORACLE_HOME'}="/opt/oracle/9.0.1";my $db = "TRCH";my $user = "username";my $pass = "password";my $dbh = DBI->connect("dbi:Oracle:$db",$user, $pass)|| die "ERROR: $DBI::errstr ";

... ... ... ... ...

... ... ... ... ...$dbh->disconnect;

Executing SQL Statements Select Statements Non-Select Statements

Page 28: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

DBI – Non-Select Statement

$sth = $dbh->prepare(“insert into person values(?)”);

$rv = $sth->execute( $baz );$sth->finish; The return value of the call: $rv

$rv is number of rows changed need to call finish on the statement handle when it is

no longer needed execute fills in the question marks (?) in the prepare

statement with the arguments; automatically escapes any character that may be needed

such as “ or \

Page 29: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

DBI – Select Statements$sth = $dbh->prepare("SELECT foo, bar FROM table

WHEREbaz=?");$sth->execute( $baz );my @row;while ( @row = $sth->fetchrow_array ) { print "foo is $row[0] and bar is $row[1]\n"; }$sth->finish;

the while loop fetches the results from the select into a list one row at a time

Can also get number of rows returned by select statement via

$sth->rows;

Page 30: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

CGI/DBI Example

Simple Forms user submits name and it is put into a database

HTML Page with Form for user to input name Perl-CGI Script to process the form and insert the data

into the Oracle Database; also print out message Uses both CGI and DBI

display all names in the database Perl-CGI script to extract data from Oracle Database and

Display to User uses both CGI and DBI

Page 31: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

CGI/DBI Example – HTML File

User Form input.html http://torch.cs.dal.ca/~swang/4173/input.html

Process User Input input.cgi http://torch.cs.dal.ca/~swang/4173/input.txt

Display All Daqta disp.cgi http://torch.cs.dal.ca/~swang/4173/disp.txt

Page 32: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

CGI/DBI Example – Input Script Filename: input.cgi (input.cgi.txt)

<html><head><title>CSCI 4173</title></head><body>Input Name:<form method="GET" action="cgi-bin/input.cgi"><input type="text" name="name" size="12"><input type="submit" value="Submit Form!"><input type="reset" value="Clear Form!"></body>

Page 33: Perl for People Singer XJ Wang Learning Center Available At: swang/4173/pfp.pptswang/4173/pfp.ppt.

Other Resources Perl Documentation : perldoc

For modules perldoc [moduleName] perldoc DBI perldoc CGI

For functions perldoc -f [functionName] perldoc -f printf perldoc -f chomp

CS Online Perl Books : http://www.library.dal.ca/subjects/csci_ebks.htm

Learning Perl Perl and CGI for the World Wide Web Advanced Perl Programming