Perl for People Singer XJ Wang Learning Center Available At:

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.
1/12 Steven Leung Very Basic Perl Tricks A Few Ground Rules File I/O and Formatting Operators, Flow Control Statements Regular Expression Subroutines Hash.
Programming Perls* Objective: To introduce students to the perl language. –Perl is a language for getting your job done. –Making Easy Things Easy & Hard.
CSET4100 – Fall 2009 Perl Introduction Scalar Data, Operators & Control Blocks Acknowledgements: Slides adapted from NYU Computer Science course on UNIX.
Browsers and Servers CGI Processing Model ( Common Gateway Interface ) © Norman White, 2013.
CS311 – Today's class Perl – Practical Extraction Report Language. Assignment 2 discussion Lecture 071CS Operating Systems I.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Scalar Variables Start the file with: #! /usr/bin/perl –w No spaces or newlines before the the #! “#!” is sometimes called a “shebang”. It is a signal.
CSC3530 Software Technology Tutorial Two PERL Basics.
CGI programming in Perl Learning Objectives: 1. To understand how a CGI program works in Perl and how to make it runnable in web browsers 2. To learn how.
Perl Lecture #1 Scripting Languages Fall Perl Practical Extraction and Report Language -created by Larry Wall -- mid – 1980’s –needed a quick language.
Perl File I/O and Arrays. File I/O Perl allows to open a file to read, write, or append As well as pipe input or output to another program. —We get to.
Guide To UNIX Using Linux Third Edition
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  PHP is interpreted  PHP code is embedded into HTML code  interpreter.
2440: 141 Web Site Administration Web Server-Side Programming Professor: Enoch E. Damson.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
Chapter 9 Using Perl for CGI Programming. Computation is required to support sophisticated web applications Computation can be done by the server or the.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
INTERNET APPLICATION DEVELOPMENT For More visit:
Set 5: Perl and Database Connections
Chapter 5 Java Script And Forms JavaScript, Third Edition.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
NMED 3850 A Advanced Online Design January 26, 2010 V. Mahadevan.
School of Computing and Information Systems CS 371 Web Application Programming PHP - Basics Serving up web pages.
USING PERL FOR CGI PROGRAMMING
(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.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
Website Development with PHP and MySQL Saving Data.
1 Basic Perl CGI Programming. 2 Issues How and when your program is invoked. Generating Response –HTTP Headers –HTML (or whatever document type you want)
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
Databases On The Web with perl Archie Warnock
Books. Perl Perl (Practical Extraction and Report Language) by Larry Wall Perl 1.0 was released to usenet's alt.comp.sources in 1987 Perl 5 was released.
Perl Language Yize Chen CS354. History Perl was designed by Larry Wall in 1987 as a text processing language Perl has revised several times and becomes.
Perl: Lecture 1 The language. What Perl is Merger of Unix tools – Very popular under UNIX – shell, sed, awk Programming language – C syntax Scripting.
3 1 Sending Data Using an Online Form CGI/Perl Programming By Diane Zak.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
Introduction to Programming the WWW I CMSC Winter 2003.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
David Lawrence 7/8/091Intro. to PHP -- David Lawrence.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Getting started in Perl: Intro to Perl for programmers Matthew Heusser – xndev.com - Presented to the West Michigan Perl User’s Group.
Perl, CGI and DBI Ashley George March 7th, 2005.
Shell Scripting – Putting it All Together. Agenda Escaping Characters Wildcards Redirecting Output Chaining and Conditional Chaining Unnamed and Named.
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.
Implementing and Using the SIRWEB Interface Setup of the CGI script and web procfile Connecting to your database using HTML Retrieving data using the CGI.
A Few More Functions. One more quoting operator qw// Takes a space separated sequence of words, and returns a list of single-quoted words. –no interpolation.
Introduction to Perl NICOLE VECERE. Background General Purpose Language ◦ Procedural, Functional, and Object-oriented Developed for text manipulation.
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
 2001 Prentice Hall, Inc. All rights reserved. Chapter 7 - Introduction to Common Gateway Interface (CGI) Outline 7.1Introduction 7.2A Simple HTTP Transaction.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
8 th Semester, Batch 2009 Department Of Computer Science SSUET.
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.
Introduction to Programming the WWW I CMSC Winter 2003 Lecture 17.
Operators. Perl has MANY operators. –Covered in Chapter 3 of Camel –perldoc perlop Many operators have numeric and string version –remember Perl will.
Perl Subroutines User Input Perl on linux Forks and Pipes.
Radoslav Georgiev Telerik Corporation
University of Kansas Department of Electrical Engineering and Computer Science Dr. Susan Gauch April 21, 2005 I T T C Introduction to Web Technologies.
Chapter 7 - Introduction to Common Gateway Interface (CGI)
Session 2 Basics of PHP.
DBW - PHP DBW2017.
Intro to PHP & Variables
Perl Database – Just Enough
Lesson 2. Control structures File IO - reading and writing Subroutines
Presentation transcript:

Perl for People Singer XJ Wang Learning Center Available At:

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 %hashVariable;

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”;

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

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 Any position in list that hasn’t been explicitly defined has the value refers to the list as a whole, $ refers to = (“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

List Variables (con’t) Sorting: Alphabetically = Numerical = sort {$a reversed = Accessing $scalarVariable = $list[4]; $scalarVariable = $list[$index]; Setting $list[5] = ‘cat’; $list[$index] = $nameOfPerson; $list[8] = 5; Getting Number of Elements in a List: $numElements =

List Variables (con’t) Operation at Head of List (low index): Insertion  $scalar; Deletion --> $scalar = Operation at Tail of List (high index): Insertion  $scalar; Deletion  $scalar = Combining Lists and = = Combinining Multiple = NOTE: does not form multi-dimensional lists, instead creates one list with elements from both parts

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”;

Hash Variables (con’t) Copying is done through assignment (each element is copied) %copy = %original; Lists of Keys/Value List of Keys = keys %hash; List of 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

Hash Variables (con’t) Hash from List %hash 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 = %hash; Every even element becomes key for odd element (the odd element after the even one) Order of the elments are not gauarneteed

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  WrongRight if ($a == 5 ) print “hello world”; else print “world hello”; if ($a == 5 ){ print “hello world”; } else{ print “world hello”; }

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 ){ 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 ){

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

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 ;

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 = ; Write to file: print FILE “hello wrold”; Sample Program: open(FILE, "file.txt"); open(FILE2, ">out.txt"); my $line; while( $line = ){ print FILE2 $line; } close(FILE); close(FILE2);

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”;

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

Subroutines (con’t) sub sample1{ grabs all remaining empty my ….. } sub sample2{ grabs rest of arguments if any my ($var1, ….. } = (“a”, “b”, “c”); = (“c”, “d”, “e”); my $v1 = “alpha”; my $v2 = “beta”; # 1 sample1($v1, # 2 # 3 sample2($v1, # 4 the first list that is part of the argument list in the subroutine takes all remaining arguments; the second list is empty

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 = $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

References (con’t) sub changeL{ my $listRef = $_[0]; $listRef->[0] = “ABA”; } = (“BAB”); my $listR = print “$list[0]\n”; changeL($listR); print “$list[0]\n”; Results when Run  BAB ABA

Sample Program #!/usr/bin/perl -w # # this is a comment use strict; sub printHello{ my ($name, $number) print "Hello $name, welcome to World!\n"; return ($number*2, $number+4); } print "Enter Your Name: "; my $nA = ; chomp($nA); print "Enter Your Age: "; my $nB = ; chomp($nB); my ($returnA, $returnB) = printHello($nA, $nB); print "$returnA is first and $returnB is second\n";

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

CGI (con’t) Running Perl-CGI on Borg/Torch/Locutus: ensure that your web page is accessible and has correct permissions Setup the scripts as following: 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

CGI (con’t) 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

CGI (con’t) 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(“other”);

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

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

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 \

DBI – Select Statements $sth = $dbh->prepare("SELECT foo, bar FROM table WHEREbaz=?"); $sth->execute( $baz ); while = $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;

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

CGI/DBI Example – HTML File User Form input.html Process User Input input.cgi Display All Daqta disp.cgi

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

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 : Learning Perl Perl and CGI for the World Wide Web Advanced Perl Programming