Download presentation
Presentation is loading. Please wait.
Published byÉloïse Gauthier Modified over 5 years ago
1
Perl Fundamentals Introduction to Perl as a Server-Side Technology
Week 4: Perl - I Perl Fundamentals Introduction to Perl as a Server-Side Technology
2
Perl “Practical Extraction and Report Language” Invented by Larry Wall
Wall’s goal: “Easy things should be easy and hard things should be possible.” Eclectic blend of features from several languages Often used as an active Web-server scripting language Responds to an HTTP request by generating the HTML for the response page Typically also saves user data and/or retrieves data for the response. Also popular for building system admin tools COMP/DCOM 461 – CWB
3
The Role of Perl in Server-Side Response Handling and Page Generation
Browser Server POST or GET HTTP (Web) Server Form Response Page ValidationResult ValidationRequest URL HTTP Parameters Response Page (HTML) JavaScript Code Perl COMP/DCOM 461 – CWB
4
A Simple Perl Script #!/bin/perl
Invoke Perl to handle this script Required HTTP header #!/bin/perl print "Content-type: text/html", "\n"; print "\n"; print "<html> <head> <title>First Perl Script</title></head>\n"; print "<body>\n"; print "Hello World!\n"; print "</body></html>\n"; exit(0); End of HTTP headers End of Content Tell Web server that everything is OK COMP/DCOM 461 – CWB
5
Note All double quotes in these slides should be ", not “ and ”, which may be accidentally inserted by PowerPoint COMP/DCOM 461 – CWB
6
Using Perl on Tomcat All Perl scripts must be installed in the directory WEB-INF/cgi under your webapp (or webappw) Use .pl as the file extension (Optional) The script file must be readable by “other” – that is, chmod 604 myfile.pl URL (replace my ID with yours): COMP/DCOM 461 – CWB
7
A Snippet from WEB-INF/web.xml
<!-- define mapping for the CGI servlet --> <servlet-mapping> <servlet-name>cgi</servlet-name> <url-pattern>/cgi-bin/*</url-pattern> </servlet-mapping> Maps all URLs /cgi-bin/* to the built-in CGI-handling servlet You’ll find such a mapping in the WEB-INF/web.xml file in your webapp directory. COMP/DCOM 461 – CWB
8
More from WEB-INF/web.xml
<!-- define the servlet that executes CGI scripts --> <servlet> <servlet-name>cgi</servlet-name> <servlet-class> org.apache.catalina.servlets.CGIServlet </servlet-class> <init-param> <param-name>clientInputTimeout</param-name> <param-value>100</param-value> </init-param> <param-name>debug</param-name> <param-value>6</param-value> <param-name>cgiPathPrefix</param-name> <param-value>WEB-INF/cgi</param-value> <load-on-startup>1</load-on-startup> </servlet> Look in the WEB-INF/cgi directory to find the scripts COMP/DCOM 461 – CWB
9
Checking Your Script To “compile” your script to check out its syntax:
perl –c filename To run your script outside of Tomcat: perl filename Beware that the ENV variable will not have any HTTP information, so you won’t have any request parameters available. COMP/DCOM 461 – CWB
10
CGI “Common Gateway Interface”
A convention for running external commands to handle HTTP requests. Information about the URL and the HTTP headers is loaded into known environment variables Perl makes them available to programmers in a built-in hash table called ENV. COMP/DCOM 461 – CWB
11
Simple Request in Perl #!/bin/perl $query = $ENV{'QUERY_STRING'};
The variable query will become the portion of the URL past the ‘?’. #!/bin/perl $query = $ENV{'QUERY_STRING'}; print "Content-type: text/html", "\n"; print "\n"; print "<html> <head> <title>Simple Query in Perl</title></head>\n"; print "<body>\n"; print "The query string from the URL is $query\n"; print "</body></html>\n"; exit(0); The query variable is “interpolated” into the string. COMP/DCOM 461 – CWB
12
First Observations on Perl
Variables are indicated by a $ A variable mentioned in a string is interpolated – its value is inserted into the string. The print function outputs a comma-separated list of strings Use \n to get a newline. Script ends with exit(0); CGI information available as $ENV{'something'} Comments: # comments out the rest of the line See next slides. COMP/DCOM 461 – CWB
13
Selected CGI Parameters
$ENV{'REQUEST_METHOD'} – GET or POST $ENV{'QUERY_STRING'} – URL after the ‘?’ $ENV{'CONTENT_LENGTH'} – number of bytes in the content (for POST only) $ENV{'SCRIPT_URI'} – URL up through the script filename (excluding any ?-string or #-name) $ENV{'REQUEST_URI'} – Complete URL, excluding #-name $ENV{'HTTP_USER_AGENT'} – Browser identification $ENV{'HTTP_XXXXX'} – HTTP header xxxxx COMP/DCOM 461 – CWB
14
Dump of the ENV Values We’ll cover the features of Perl used in this example in more detail later. COMP/DCOM 461 – CWB
15
Exercise – Perl Cookie Generator
Write a Perl script that sets a cookie in the browser It should return a page that displays any cookies found in the request Hint: Recall the “Set-Cookie” and “Cookie” HTTP headers COMP/DCOM 461 – CWB
16
My Solution Code: Test:
Test: COMP/DCOM 461 – CWB
17
Selected Perl Features in More Detail
18
Perl Variables $abc – a scalar variable called “abc”
@def – an array variable called “def” %ghi – a hashtable variable called “ghi” scalar: having a single value COMP/DCOM 461 – CWB
19
The my Operator Normally variables are global
To get a local variable, use the my operator: my $name = “Anthony”; = (1,2,5,8..20); COMP/DCOM 461 – CWB
20
More on Scalars Indicated by a leading $
Think of the $ as meaning “Treat the following as a scalar” Holds one value Can be number or string: $a = "wxy"; $b = 8; Reference using the $ as well: $a = $b; COMP/DCOM 461 – CWB
21
More On Arrays @a means treat a as an array
An array holds a list of values: @def = (1, 2, "zzz", ); Each value must be a scalar: $abc = $def[3]; Think: $def[3] means “treat def[3] as a scalar” Arrays count from 0 COMP/DCOM 461 – CWB
22
Array Slices @a[2,5,6] is an array consisting of items 2, 5, and 6 taken from array a @a[2..5] picks items 2, 3, 4, and 5 @a = (1, 3, "a", "u", 9); print #prints: a 9 print #prints: a u 9 COMP/DCOM 461 – CWB
23
Initializing Arrays List notation: Quoted word notation:
@a = (1, 3, “aaa”, “bbb”, 0); Quoted word notation: @a = qw/1 3 aaa bbb/; Each white-space-separated word becomes a string member of the list. COMP/DCOM 461 – CWB
24
The sort Array Function
Block sort {$a - Returns sorted array The block in {…} is a little anonymous subroutine that is evaluated for each comparison $a and $b are the items to compare The value should be positive if $a > $b, negative if $b > $a, and zero if $a equals $b The example given sorts the array as numbers Use { $a cmp $b } for alphanumeric comparison COMP/DCOM 461 – CWB
25
More Array Functions reverse @a
produces an array in the reverse order of a produces an array of the members of a that match the pattern Use the same pattern syntax as with JavaScript COMP/DCOM 461 – CWB
26
More on Hashtables Officially known as associative arrays
A hashtable holds a set of values accessed by keys that are strings %ghi = ("xyz", 4, "wxy", "q", "vwx", 19); $abc = $ghi{"xyz"}; $ghi{"xyz"} means “treat ghi{"xyz"} as a scalar” Every other item is a key; the other items are values Extract the member with the key “xyz” COMP/DCOM 461 – CWB
27
More on Hashtables Two ways to initialize:
Every other item is a key; the other items are values Two ways to initialize: %capitals = (“Ohio”, “Columbus”, “Illinois”, “Springfield”, “Virginia”, “Richmond”); %capitals = (Ohio => “Columbus”, Illinois => “Springfield”, Virginia => “Richmond”); => works like a comma and also implies that the previous word is a string COMP/DCOM 461 – CWB
28
Built-in Functions For Hashes
each(%a) – returns a different ($key,$val) list each time it’s called in a loop: while(($k,$v) = each(%a)){ … } keys(%a) – returns a list of the keys values(%a) – returns a list of the values delete $a{'qqq'} – deletes member qqq Note list assignment feature COMP/DCOM 461 – CWB
29
Using each in a While Loop
while(($k,$v) = each(%a)){ print "Key: $k Value: $v\n"; } COMP/DCOM 461 – CWB
30
The List Assignment Feature
($a, $b, $c) = (900, "cat", 9); Assigns 900 to a “cat” to b 9 to c COMP/DCOM 461 – CWB
31
Perl Strings Single quotes: treat the string literally
Double quotes: the string is “interpolated” That is, variables are interpreted and inserted in the string: $a = “World”; $b = “Hello $a”; $b becomes “Hello World”; COMP/DCOM 461 – CWB
32
Here Documents A mechanism for creating a long, multi-line string
print <<end; <body> <p>Hello, $userName!</p> </body> end Variables in the here-document are interpolated So the paragraph becomes, say, “Hello, Bill!” Means all text up to the line starting with “end” COMP/DCOM 461 – CWB
33
foreach Loops Repeats code for each member of an array Syntax:
foreach my $x { … } Repeats the code in { … } for each member of the array cats Sets the (local) variable x to the corresponding member The my is optional, but makes x a local variable COMP/DCOM 461 – CWB
34
Implementation of the Dump of the ENV Hashtable
Code snippit: print "<table>\n"; foreach my $key (keys %ENV) { print "<tr><td>$key</td><td>$ENV{$key}</td>\n"; } print "</table>\n"; The keys function extracts a list of the keys in a hashtable COMP/DCOM 461 – CWB
35
Alternative Implementation
Code snippit: print "<table>\n"; while ((my ($key, $val) = each(%ENV))) { print "<tr><td>$key</td><td>$val</td>\n"; } print "</table>\n"; The each function returns a 2-element list: one key and one value COMP/DCOM 461 – CWB
36
Exercise – Simple Perl Coding
Write a Perl script to generate a table of values The table should have two columns, representing the keys and values in a hashtable Create the hard-coded hashtable using either type of hash initializer COMP/DCOM 461 – CWB
37
Comparisons Numerical comparisons:
<=> and cmp return -1, 0, or 1, depending on whether left side is <, =, or > the right side Numerical comparisons: < <= == != >= > <=> String comparisons: lt le eq ne ge gt cmp if($name eq “Fred”) if($orderNumber == ) COMP/DCOM 461 – CWB
38
Comparison Demo http://cs.franklin.edu:8461/brownc/cgi-bin/cmp.pl?4
Code: COMP/DCOM 461 – CWB
39
Arrays of Hashtables Each array member is a hashtable
my $theOrderId = "18918"; @orders = ( { orderId => "18994", status => "hold", item => "socks" }, { orderId => "18918", status => "shipped", item => "pork bellies" } ); my $theStatus = "unknown"; for($i = 0; $i $i++) { if ( $orders[$i]{orderId} eq $theOrderId) { $theStatus = $orders[$i]{status}; } print "The status of order $theOrderId is: <b>$theStatus</b>.\n"; Each array member is a hashtable Extract the orderId element from the ith member of the orders array. COMP/DCOM 461 – CWB
40
Hashtables of Hashtables
my $theOrderId = "18918"; %orders = ( "18994" => { status => "hold", item => "socks" }, "18918" => { status => "shipped", item => "pork bellies" } ); if(($theStatus = $orders{$theOrderId}{status} )) { print "The status of order $theOrderId is: <b>$theStatus</b>.\n"; else print "The order $theOrderId is unknown\n" Each hashtable member is another hashtable Extract the status member from the orderId member of the orders array. COMP/DCOM 461 – CWB
41
Perl References Assigned readings in Anderson-Freed Syntax:
Built-in Functions: COMP/DCOM 461 – CWB
42
Homework Assignment This week you will just be getting used to Perl by generating the Order Status page For now, put your order data in an array or other Perl structure that you wish Include at least two orders Write Perl print statements to generate the HTML code like you have in your current page design Insert the order information from the array into the HTML Next week you will add some more Perl functionality Accessing the order data from in a file Using a userID to select a particular user’s data COMP/DCOM 461 – CWB
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.