Survey of Advanced Perl Topics - PowerPoint PPT Presentation

1 / 17
About This Presentation
Title:

Survey of Advanced Perl Topics

Description:

... your objects hide all their functionality, pretending to be ordinary variables ... what type of variable should your object pretend to be? ... – PowerPoint PPT presentation

Number of Views:28
Avg rating:3.0/5.0
Slides: 18
Provided by: pauld98
Category:

less

Transcript and Presenter's Notes

Title: Survey of Advanced Perl Topics


1
Survey of Advanced Perl Topics
  • Database access
  • "OpSys"-like functions
  • Signal Handling
  • Tieing

2
Database Access
  • Standardized through the DBI module
  • not core module, but installed on CS system
  • Differing Database systems have their own DB
    driver module
  • DBDmysql, DBDOracle, DBDInformix, etc
  • By simply changing which DBD you use, your
    existing code can work with a new database.
  • Check the FAQ at http//www.cs.rpi.edu/lab/labmanu
    al.html for generic instructions on setting up a
    DB on CSNet

3
General Format of Perl DBI
  • declare a "DataBase Handler" to connect to the DB
  • define SQL statement(s)
  • prepare the SQL, returning "STatement Handler(s)"
  • execute the statement handlers
  • fetch the results from the statement handlers, if
    apporpriate

4
DBI Example
  • use DBImy dsn 'DBImysqldatabaselallip_db
    hostbarbara.cs.rpi.eduport1234'my dbh
    DBI-gtconnect(dsn,user,password)
  • my sql "SELECT FROM players "sql .
    "WHERE score gt ? AND score lt ?"
  • my sth dbh-gtprepare(sql)sth-gtexecute(mins
    core, maxscore)
  • while (my r sth-gtfetchrow_hashref) print
    "r-gtname's score r-gtscore\n"
  • - You can use the same sth to now execute the
    prepared SQL with different values

5
Fetching Methods
  • fetchrow_hashref
  • fetch "next" row, as a hash reference (key
    column name, value field value)
  • fetchrow_arrayref
  • fetch next row, as an array reference (in order
    defined by the table)
  • fetchrow_array
  • fetch next row as an array
  • fetchall_arrayref
  • fetch entire results
  • no parameters - entire table as arrayref of
    arrayrefs
  • pass array ref - select numbers of which columns
    of entire table to return
  • pass hashref - select names of which columns to
    return, and return as an array of hash referneces
  • pass empty hashref - return entire table as array
    of hash references
  • fetchall_hashref(key)
  • fetch entire results, as a hashref of hashrefs.
    Key is index of table

6
DBI errata
  • if you don't need to fetch (an UPDATE, INSERT, or
    DELETE statement),
  • just use do(). No need to prepare or execute
  • dbh-gtdo('DELETE FROM class WHERE drop 1')
  • sth-gtrows returns the number of rows inserted,
    updated, or deleted.
  • DOES NOT return number of rows that are selected!
  • SQL NULL gt Perl undef
  • dbh-gtRaiseError 1, Perl will die on any SQL
    error.
  • (Otherwise, must check return value of every db
    call, and then check DBIerr)
  • http//dbi.perl.org perldoc DBI

7
"OpSys-like" functions
  • touched on these earlier in the semester
  • basically said "Don't do that".
  • please, take extreme caution when using these
    functions
  • listing of Perl equivalents only
  • for more information about the internals of Unix,
    take OpSys

8
fork()
  • split off a separate process, duplicating the
    code and environment
  • return value in parent is child's new pid
  • return value in child is 0
  • my pid fork()if (pid) parent print
    "Child pid just forked off\n"
    do_parent_stuff() else print "I'm the
    child, just spawned\n" do_child_stuff()

9
wait()
  • wait for one of the child processes to finish
  • returns the PID of the child that just finished
  • ? is set to the exit status of the child that
    was just found with wait
  • waitpid(pid)
  • wait for a specific child to exit

10
exec(cmd, _at_args)
  • Execute cmd, passing _at_args to that command
  • executes IN THE CURRENT PROCESS, wiping out
    anything else this code was going to do
  • Example I have an if statement in hw_submit.pl
    so that if you tried using it to submit hw4, it
    exec'ed hw_submit4.pl
  • therefore, has no return value
  • any code below the exec (other than a warning
    that the exec failed) is meaningless.
  • retval system(cmd, _at_args) is equivalent to
  • if (my pid fork()) waitpid(pid) retval
    ? else exec (cmd, _at_args)

11
Signal Sending
  • Processes can send signals to one another.
  • Most common use is to tell a process to die
  • Therefore, function to do this is kill
  • kill(pid, signal)
  • to see which signals are available, run kill -l
    on your system
  • By default, most (all?) signals result in program
    termination
  • Most shells respond to a CTRL-C by sending the
    current process a SIGINT

12
Signal Handling
  • With the exception of SIGKILL (9) and SIGSTOP
    (23), all signals can be caught and processed.
  • If your program receives a certain signal, you
    can decide what to do about it.
  • Assign a reference to the handler subroutine to
    the SIG hash, where the key is the 'name' of the
    signal
  • signal name also passed as first argument to the
    subroutine.
  • SIGINT sub print "Bwaha, your CTRL-C
    doesn't scare me!"
  • Now, if the user tries to CTRL-C your program,
    the message will be printed out instead of the
    program dieing.
  • (To actually kill this script, find out its pid
    from ps -u ltrcsidgt, and then send it a SIGKILL
    kill -9 ltpidgt)

13
Tieing
  • a method by which you can make your objects hide
    all their functionality, pretending to be
    ordinary variables
  • Example TieFile
  • hides functionality of a class in an ordinary
    array
  • "tie" an array to a file.
  • accessing elements of the array is now equivalent
    to accessing lines of the file
  • push, pop, splice, foon, etc all Do The Right
    Thing

14
Tieing your own classes
  • perldoc perltie
  • constructor TIESCALAR, TIEARRAY, TIEHASH
  • what type of variable should your object pretend
    to be?
  • Create your object, just as you would in any
    other constructor.
  • Define your object however you like, probably as
    a hashref
  • User will call your object's constructor using
    the tie() function
  • tie my sca, 'TieMyObj'
  • tie my _at_arr, 'TieMyObj', 'alpha', 'beta'
  • tie my hsh, 'TieMyObj'

15
Tied methods
  • For scalars FETCH and STORE
  • define FETCH to take one argument - the object,
    and return whatever value should be returned when
    the user "reads" the object
  • define STORE to take two args - the object, and
    the value to store, make appropriate changes to
    the object when user "writes" to it
  • For arrays FETCH and STORE take additional
    argument - index user wants to retrieve or write
    to.
  • Also FETCHSIZE and STORESIZE for when array used
    in scalar context or the arr variable is used
  • Also PUSH, POP, SHIFT, UNSHIFT, SPLICE subs
    that define what happens if user uses these
    functions on the array

16
Tied Hash Methods
  • For hashes FETCH/STORE also take a key
  • EXISTS, DELETE
  • also each take a key. EXISTS should return true
    if the key is "in" the hash DELETE should remove
    the key from the hash
  • FIRSTKEY
  • Called the first time Perl processes the keys()
    or each() function. Should return the "first"
    key from the list of keys of the hash.
  • NEXTKEY
  • Called each subsequent time Perl processes the
    keys() or each() function (within a loop). Takes
    the previous key as an argument, and should
    return the "next" key.
  • SCALAR
  • called when hash is used in a scalar context

17
Recommended Further Reading
  • Advanced Perl Programming, Simon Cozens
  • Introspection, parsing beyond Regexps,
    Templating, Databases, Unicode, Event Driven
    Programming, Embedding C in Perl
  • Higher Order Perl, Mark Jason Dominus
  • Recursion Callbacks, Dispatch Tables,
    Iterator-based programs, Parsing Infinite
    Streams, "Higher-Order" functions, Program
    transformations
  • Perl Best Practices, Damian Conway
  • Tips and Advice for writing clean, elegant,
    maintainable Perl program
Write a Comment
User Comments (0)
About PowerShow.com