Perl for People - PowerPoint PPT Presentation

About This Presentation
Title:

Perl for People

Description:

... value for the same key, then the first value gets overwritten ... If two even elements (potential keys) are the same, then the result is not deterministic ... – PowerPoint PPT presentation

Number of Views:54
Avg rating:3.0/5.0
Slides: 34
Provided by: singe9
Category:
Tags: keys | people | perl

less

Transcript and Presenter's Notes

Title: Perl for People


1
Perl for People
  • Singer XJ Wang
  • Learning Center

Available At http//www.cs.dal.ca/swang/4173/pfp
.ppt
2
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 _at_listVariable
  • my hashVariable

3
Scalar Variables
  • Either a number or a string of characters
    (doesnt 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

4
Scalar Variables (cont)
  • 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 ? lt, lt, , !, gt, gt
  • if ( a lt b )
  • numerical comparison is made
  • String Context ? lt, le, eq, ne, ge, gt
  • if ( a eq b )
  • alphabetical comparison is made

5
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 _at_
  • Any position in list that hasnt been explicitly
    defined has the value undef
  • _at_ refers to the list as a whole, refers to
    elements
  • _at_array (elementA, elementB, elementC)
  • array2 is the 3rd element with value
    elementC
  • array5 ted ? sets the 6th element in the
    list to ted
  • Copying is done through assignment (each element
    is copied)
  • _at_copy _at_original

6
List Variables (cont)
  • Sorting
  • Alphabetically ? _at_sorted sort _at_unsorted
  • Numerical ? _at_sorted sort a ltgt b _at_unsorted
  • Reversing
  • _at_ reversed reverse _at_normal
  • Accessing Element _at_list
  • scalarVariable list4
  • scalarVariable listindex
  • Setting Element _at_list
  • list5 cat
  • listindex nameOfPerson
  • list8 5
  • Getting Number of Elements in a List
  • numElements scalar _at_list

7
List Variables (cont)
  • Operation at Head of List (low index)
  • Insertion ? unshift _at_list, scalar
  • Deletion --gt scalar shift _at_list
  • Operation at Tail of List (high index)
  • Insertion ? push _at_list, scalar
  • Deletion ? scalar pop _at_list
  • Combining Lists and Scalars
  • _at_newList (_at_listA, scalar)
  • _at_newList (scalar, _at_listA)
  • Combinining Multiple Lists
  • _at_newList (_at_listA, _at_listB)
  • _at_newList (_at_listB, _at_listA)
  • NOTE does not form multi-dimensional lists,
    instead creates one list with elements from both
    parts

8
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
  • hashkey value
  • hash5 egg
  • hashted bacon

9
Hash Variables (cont)
  • Copying is done through assignment (each element
    is copied)
  • copy original
  • Lists of Keys/Value
  • List of Keys ? _at_keys keys hash
  • List of Values ? _at_values values hash
  • Insertion/Deletion/Access hash
  • Insertion ? hashkey value
  • Deletion ? delete hashkey
  • Access ? scalarValue hashkey
  • 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

10
Hash Variables (cont)
  • Hash from List
  • hash _at_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
  • _at_list hash
  • Every even element becomes key for odd element
    (the odd element after the even one)
  • Order of the elments are not gauarneteed

11
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
12
Control Structures (cont)
  • 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 ( _at_list )
  • print element -gt scal \n
  • To print all keys and values in a hash ?
  • my scal
  • foreach scal ( keys hash )
  • print scal -gt hashscal\n
  • To sort all the keys alphabetically use this line
    instead
  • foreach scal ( sorted keys hash )

13
Input and Output
  • Reading from STDIN
  • ltSTDINgt is variable for standard in
  • Reads one line and assign it to variable a
  • chomp removes the new line at the end
  • a ltSTDINgt
  • 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

14
Input and Output (cont)
  • Printing Large Documents
  • the end marker (EOF) must immediately follow the
    ltlt
  • 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 ltltEOF
  • blah blah variable
  • blah blah blah text
  • EOF

15
Input and Output (cont)
  • Opening/Closing Files
  • Reading ? open(FILE, file.txt)
  • Writing ? open(FILE, gtfile.txt)
  • Appending ? open(FILE, gtgtfile)
  • Closing ? close(FILE)
  • FILE is a file handle, can be any other name
  • Separate from , , _at_ variables
  • File I/O
  • Read from file line ltFILEgt
  • Write to file print FILE hello wrold
  • Sample Program
  • open(FILE, "file.txt") open(FILE2, "gtout.txt")
  • my line
  • while( line ltFILEgt )
  • print FILE2 line
  • close(FILE) close(FILE2)

16
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

17
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 _at__
  • when parsing arguments in the subroutine the list
    or hash will grab all remaining elements in the
    list _at__, 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

18
Subroutines (cont)
  • sub sample1 _at_l1 grabs all remaining arguments,
    _at_l2 empty
  • my (var1, var2, _at_l1, _at_l2) _at__
  • ..
  • sub sample2 _at_rest grabs rest of arguments if
    any
  • my (var1, var2, _at_rest) _at__
  • ..
  • my _at_list1 (a, b, c)
  • my _at_list2 (c, d, e)
  • my v1 alpha my v2 beta
  • sample1(v1, v2, _at_list1, _at_list2) 1
  • sample1(v1, v2, _at_list1) 2
  • sample2(v1, v2, _at_list1, _at_list2) 3
  • sample2(v1, v2, _at_list1) 4
  • the first list that is part of the argument list
    in the subroutine takes all remaining arguments
    the second list is empty

19
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 \_at_list
  • hashRef \hash
  • Accessing the Variable being References
  • Scalar ? scalarRef
  • List ? listRef-gtindex
  • Hash ? hashRef-gtkey
  • References provides
  • way to pass multiple lists/hashes into an
    subroutines
  • a way for subroutines to change a list/hash
    passed into it

20
References (cont)
  • sub changeL
  • my listRef _0
  • listRef-gt0 ABA
  • my _at_list (BAB)
  • my listR \_at_list
  • print list0\n
  • changeL(listR)
  • print list0\n
  • Results when Run ?
  • BAB
  • ABA

21
Sample Program
  • !/usr/bin/perl -w
  • this is a comment
  • use strict
  • sub printHello
  • my (name, number) _at__
  • print "Hello name, welcome to World!\n"
  • return (number2, number4)
  • print "Enter Your Name "
  • my nA ltSTDINgt
  • chomp(nA)
  • print "Enter Your Age "
  • my nB ltSTDINgt
  • chomp(nB)
  • my (returnA, returnB) printHello(nA, nB)
  • print "returnA is first and returnB is
    second\n"

22
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

23
CGI (cont)
  • 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/basi
    c_site.php
  • Setup the scripts as following
  • http//help.cs.dal.ca/faq/tutorials/web_sites/cgi_
    script.php
  • First you will need to create a cgi-bin bin
    directory in your public_html directory mkdir
    /public_html/cgi-bin
  • Next you must grant world read and execute
    permissions on your cgi-bin directory chmod arx
    /public_html/cgi-bin or chmod 755
    /public_html/cgi-bin
  • Next you must place your CGI scripts in the
    cgi-bin directory and grant world execute
    permissions on each script chomd ax script.cgi
    or chmod 711 script.cgi
  • Your scripts can now be referenced at
    http//www.cs.dal.ca/username/cgi-bin/script.cgi

24
CGI (cont)
  • Must include the CGI module in the script
  • use CGI qw/standard/
  • Printing the context type for the browser
  • print 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

25
CGI (cont)
  • ltform methodGET actionsample.cgigt
  • ltinput type"text" name"name" size"12"gt
  • ltinput value"Submit Form!"gt
  • ltinput type"reset" value"Clear Form!"gt
  • 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)
  • _at_values param(other)

26
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
    SQLPlus (Oracle)
  • Include the module DBI in the script ? use DBI
  • Major Objects
  • dbh ? database handle
  • sth ? statement handle

27
DBI (cont)
  • 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-gtconnect("dbiOracledb",user,
    pass) die "ERROR DBIerrstr "
  • ... ... ... ... ...
  • ... ... ... ... ...
  • dbh-gtdisconnect
  • Executing SQL Statements
  • Select Statements
  • Non-Select Statements

28
DBI Non-Select Statement
  • sth dbh-gtprepare(insert into person
    values(?))
  • rv sth-gtexecute( baz )
  • sth-gtfinish
  • 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 \

29
DBI Select Statements
  • sth dbh-gtprepare("SELECT foo, bar FROM table
    WHEREbaz?")
  • sth-gtexecute( baz )
  • my _at_row
  • while ( _at_row sth-gtfetchrow_array )
  • print "foo is row0 and bar is row1\n"
  • sth-gtfinish
  • 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-gtrows

30
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

31
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

32
CGI/DBI Example Input Script
  • Filename input.cgi (input.cgi.txt)
  • lthtmlgtltheadgt
  • lttitlegtCSCI 4173lt/titlegt
  • lt/headgtltbodygt
  • Input Name
  • ltform method"GET" action"cgi-bin/input.cgi"gt
  • ltinput type"text" name"name" size"12"gt
  • ltinput type"submit" value"Submit Form!"gt
  • ltinput type"reset" value"Clear Form!"gt
  • lt/bodygt

33
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
Write a Comment
User Comments (0)
About PowerShow.com