Survey of Advanced Perl Topics Database access "OpSys"-like functions Signal Handling Inside-Out Objects.

Slides:



Advertisements
Similar presentations
Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
Advertisements

Programming MySQL, Perl COEN 351. Reading List Paul DuBois: MySQL and Perl for the Web, New Riders, 2002 Jacqueline D. Hamilton: CGI Programming 101,
Lab 9 CIS 370 Umass Dartmouth.  A pipe is typically used as a one-way communications channel which couples one related process to another.  UNIX deals.
1 CS345 Operating Systems Φροντιστήριο Άσκησης 1.
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Objected Oriented Perl An introduction – because I don’t have the time or patience for an in- depth OOP lecture series…
Introduction to Unix – CS 21 Lecture 10. Lecture Overview Midterm questions Jobs and processes description The foreground and background Controlling jobs.
Lesson 10-Controlling User Processes. Overview Managing and processing processes. Managing jobs. Exiting/quitting when jobs have been stopped.
15-213/ Intro to Computer Systems by btan with reference to Spring 10’s slides.
CS 497C – Introduction to UNIX Lecture 26: - The Process Chin-Chih Chang
UNIX Process Control Bach 7 Operating Systems Course Hebrew University Spring 2007.
VBA Modules, Functions, Variables, and Constants
Signal Signal : - is a notification sent to a process to notify it of some event - interrupts whatever the process is doing and force it to handle a signal.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Objected Oriented Perl An introduction – because I don’t have the time or patience for an in- depth OOP lecture series…
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
The Programming Interface. Main Points Creating and managing processes – fork, exec, wait Performing I/O – open, read, write, close Communicating between.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
1 CSC241: Object Oriented Programming Lecture No 27.
DBI tutorial February 5 th, What is DBI DBI is short for Database Interface, which is a Perl module DBI is short for Database Interface, which is.
1Reference “Introduction To Unix Signals Programming” in the reference material section Man page – sigprocmask, alarm “Understanding the Linux Kernel”
(Chapter 10 continued) Our examples feature MySQL as the database engine. It's open source and free. It's fully featured. And it's platform independent.
Creating and Executing Processes
CS 346 – Chapter 4 Threads –How they differ from processes –Definition, purpose Threads of the same process share: code, data, open files –Types –Support.
More on UART Interrupts; System Calls Reference on Interrupt Identification Register(IIR) slide 17 of
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Hands On UNIX II Dorcas Muthoni. Processes A running instance of a program is called a "process" Identified by a numeric process id (pid)‏  unique while.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Agenda  Working with Processes: Purpose Running Programs within same process (execl, execlp, execle, execv, execvp, execve) “Spawning” other process (fork,
Moose: A Postmodern Object System for Perl Stuart Skelton.
System calls for Process management
Scis.regis.edu ● CS 468: Advanced UNIX Class 5 Dr. Jesús Borrego Regis University 1.
1 CS 430 Database Theory Winter 2005 Lecture 14: Additional SQL Topics.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Implementing The Middle Tier These slides.
Concurrent Processes Processes can concurrently run same program. Processes can concurrently run same program. Processes can start other processes. Processes.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
1 Signals (continued) CS 241 April 9, 2012 University of Illinois.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
ITN Wake Tech1 ITN270 Advanced Internet Databases Lecture 11. The Perl DBI API - Part II Topics: – Perl DBI interface to MySQL.
UNIX Signals * POSIX-Defined Signals * Signaling Processes * Signal Mask * sigaction * kill and sigaction * alarm * Interval Timers * POSIX.1b Timers *
UNIX Command RTFM: trap(1p) Gilbert Detillieux October 8, 2013 MUUG Meeting.
Copyright 2007 Byrne Reese. Distributed under Creative Commons, share and share alike with attribution. Intermediate Perl Programming Class Three Instructor:
Process Management Azzam Mourad COEN 346.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
CP476 Internet Computing Perl CGI and MySql 1 Relational Databases –A database is a collection of data organized to allow relatively easy access for retrievals,
ACCESS CONTROL. Components of a Process  Address space  Set of data structures within the kernel - process’s address space map - current status - execution.
DBI: The Neophyte's Guide1 What is DBI? DBI = DataBase Interface DBI is database-independent DBI allows you to write code that interacts with databases.
S -1 Processes. S -2 wait and waitpid (11.2) Recall from a previous slide: pid_t wait( int *status ) wait() can: (a) block; (b) return with status; (c)
The Process CIS 370, Fall 2009 CIS UMassD. The notion of a process In UNIX a process is an instance of a program in execution A job or a task Each process.
System calls for Process management Process creation, termination, waiting.
1 Lecture 19: Unix signals and Terminal management n what is a signal n signal handling u kernel u user n signal generation n signal example usage n terminal.
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
1 Unix system calls fork( ) wait( ) exit( ). 2 How To Create New Processes? n Underlying mechanism -A process runs fork to create a child process -Parent.
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
4.1 Operating Systems Lecture 9 Fork and Exec Read Ch
Process Related System Calls By Neha Hulkoti & Kavya Bhat.
Perl Subroutines User Input Perl on linux Forks and Pipes.
COMP234 - perl Perl DBI Topics Database vs access methods DBMS and DBMS API's Relational database SEQUEL Perl DBI SQL.
...looking a bit closer under the hood
...looking a bit closer under the hood
Hands On UNIX AfNOG 2010 Kigali, Rwanda
Running external programs
Unix Process Management
Hands On UNIX AfNOG X Cairo, Egypt
Error Handling Summary of the next few pages: Error Handling Cursors.
Perl Modules.
Perl Database – Just Enough
...looking a bit closer under the hood
Tutorial: The Programming Interface
System Programming: Process Management
Presentation transcript:

Survey of Advanced Perl Topics Database access "OpSys"-like functions Signal Handling Inside-Out Objects

Database Access Standardized through the DBI module –not core module, but installed on CS system Differing Database systems have their own DB driver module –DBD::mysql, DBD::Oracle, DBD::Informix, etc By simply changing which DBD::* you use, your existing code can work with a new database system. Setting up an individual DB on CSNet is difficult, due to lacking root access. If you really need one, contact labstaff.

General Format of Perl DBI declare a "DataBase Handler" to connect to the Database define SQL statement(s) prepare the SQL, returning "STatement Handler(s)" execute the statement handlers, passing values for the bind parameters fetch the results from the statement handlers, if appropriate

DBI Example use DBI; my $dsn = 'DBI:mysql:database=game;host=db.example.com'; my $dbh = DBI->connect($dsn,$user,$password); my $sql = "SELECT * FROM players "; $sql.= "WHERE score > ? AND score < ?"; my $sth = $dbh->prepare($sql); $sth->execute($minscore, $maxscore); while (my $r = $sth->fetchrow_hashref){ print "$r->{name}'s score: $r->{score}\n"; } You can use the same $sth to now execute the prepared SQL with different values

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

DBI errata do() - combines prepare() and execute(). –if you don't need to repeatedly execute the statement –Frequently used for DELETE, UPDATE, and INSERT statements can't be used for SELECT, because there's no $sth to fetch from –$dbh->do('DELETE FROM class WHERE drop = 1'); $sth->rows() returns the number of rows inserted, updated, or deleted. –DOES NOT return number of rows that are selected! SQL NULL ==> Perl undef $dbh->{RaiseError} = 1, Perl will die on any SQL error. –(Otherwise, must check return value of every db call, and then check $DBI::err ) & perldoc DBI

"OpSys-like" functions touched on these in the "external commands" presentation that we didn't cover in lecture. –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

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(); }

wait() If there are any running children processes, waits for one of them to finish, and returns the PID of that child –$? is set to the exit status of the child that was just found with wait If there are no remaining running children, immediately returns -1 waitpid($pid, 0) –wait for a specific child to exit

Execute $cmd, to that command executes IN THE CURRENT PROCESS, wiping out anything else this code was going to do therefore, has no return value any code below the exec (other than a warning that the exec failed) is meaningless. $retval = is equivalent to: if (my $pid = fork()){ #duplicate process waitpid($pid);#parent wait for child to exit $retval = $?; #exit status of child } else { exec #child executes $cmd }

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($signal, $pid); –$signal is a number or signal name 6, 'SIGABRT', or 'ABRT' to see which signals are available, run ` kill -l ` on your system By default, signals result in program termination Most shells respond to a CTRL-C by sending the current process a SIGINT

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. $SIG{INT} = 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 `, and then send it a SIGKILL: `kill -9 `)

Signal Yourself There is one signal that's a little more special. ALRM - used to set an alarm clock for yourself. alarm($seconds) - $seconds from now, send yourself (ie, the current process) a SIGALRM signal Before calling alarm(), set a signal handler in $SIG{ALRM} for what you want to do when this signal is received. Only one alarm can be set at once –additional calls cancel the previous alarm return how many seconds remaining until alarm would have gone off –alarm(0) to cancel alarm without setting new.

Advanced Perl Objects As we've seen, Perl's notion of objects were kludged into the code Perl's OO is lacking keywords and definitions of a "real" Object Oriented system Many attempts have been made to remedy this The latest and greatest: Moose Full blown Object Oriented layer on top of Perl –Inheritance, Inspection, Interfaces, Polymorphism, Hard typing, Triggers, etc

Moose Several new keywords for you to define your class package Point; use Moose; has x => ( isa => 'Int', is => 'rw', required => 1, ); has y => ( isa => 'Int', is => 'rw', required => 1, );

Attribute Options is is one of "rw" or "ro" –rw => "Read/Write". The corresponding method both returns the attribute's value, and allows it to be set. –ro => "Read Only". The corresponding method only returns the attribute's value. isa is the type of data the attribute contains –Str, Num, Int, ArrayRef, Object,, etc required => 1 if the user must pass the arg into the constructor default sets initial value of arg not passed in –Can be a non-ref scalar, or a subroutine reference

Moose Methods sub show { my $self = shift; my ($x,$y) = ($self->x(), $self->y()); print "($x, $y)\n"; } sub reset { my $self = shift; $self->x(0); $self->y(0); } x() and y() methods were created by the attribute definitions

Moose Subtyping You can create your own types for attributes. use Moose::Util::TypeConstraints;... subtype 'octnum' => as 'Str' => where { /^0[0-7]+$/ } => message {"$_[0] not a valid octal num"}; has permissions => ( is => 'rw', isa => 'octnum' default => '0775' );

Moose Triggers You can setup methods to be called before or after any other method is called. sub withdraw { my $self = shift; $self->{bal} -= shift; } sub deposit { my $self = shift; $self->{bal} += shift; } after qw/withdraw deposit/ => \&show_bal; sub show_bal { print "balance: $_->{bal}\n"; }

Moose Subclassing To create a subclass, use the 'extends' keyword: package Person; use Moose; #... 1; package Student; use Moose; extends 'Person'; has id_num => ( is => 'ro', isa => 'Num', required => 1); 1; Student retains all the attributes, methods, triggers, etc of Person.

Moose location & documentation Moose is a CPAN module. Not installed on CSNet. use lib "/cs/lallip/lib/perl5/site_perl/5.10.0/"; Read "Moose::Intro" and "Moose::Manual" on the CPAN –or export PERL5LIB=/cs/lallip/lib/perl5/site_perl/ perldoc Moose::Intro perldoc Moose::Manual

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 programs