400 likes | 555 Views
Introduction to Programming the WWW I. CMSC 10100-1 Winter 2003. A Crash Course in Perl. Variables: scalar, array, hash HTML forms CGI Files -- reading and writing. Variables. All variables in Perl are prefixed with a special character: $ for scalar values: $x
E N D
Introduction to Programming the WWW I CMSC 10100-1 Winter 2003
A Crash Course in Perl • Variables: • scalar, array, hash • HTML forms • CGI • Files -- reading and writing
Variables • All variables in Perl are prefixed with a special character: • $ for scalar values: $x • @ for list values: @list • % for hash values: %hash • Both numbers and strings can be scalars • Arrays are very similar to Javascript • Hashes are “associative arrays”
Scalar variables • For numerical values, we can add, subtract, multiply, divide, assign as in Javascript: $x = 42; $y = 63; $z = $x + $y - 32;
String variables $foo=“Hello world”; $bar=“I’m joining the circus”; • String concatentation: $foo . $bar • String repitition: $foo x 3
Printing scalar data • Double quotes vs. single quotes: print “$foo”; #prints Hello World print ‘$foo’; #prints $foo print “\$foo”; #prints $foo • Can print result of operations: print “Hello “ . “World”; print $foo x 3;
List variables • Creating a list: @mylist = (42,64,”foo”); • Accessing elements of a list: $mylist[0] = 33; • How long is a list? $length = $#mylist + 1; print “$length\n”;
Adding and removing items @classes=(‘Math’,’CS’,’History’); • To add or remove from beginning: $class = shift(@classes); unshift(@classes,’Dance’); • To add or remove from end $class = pop(@classes); push(@classes,’English’);
Doing stuff to each element @classes = (“Math”,”English”,”CS”); for (my $i=0;$i<=$#classes;$i++) { $classes[$i] = “Honors “ . $classes[$i]; } foreach $class (@classes) { print $class . “\n”; }
Split and join • If you have a line of text like: $foo = “Herbert::Smith::555-1234”; • You can split it into three parts by ($last,$first,$num) = split /::/,$foo; • Or store the results in an array @mydata = split /::/,$foo; • You can reverse the process $packed = join (“::”,@mydata);
Hash Variables • A list of name/value pairs (dictionary) %grades = (“Bob”=>42,”Jane”=>45,”Jim”=>90); • Lookup/edit in the list by key: print $grades{“Bob”} . “\n”; $grades{“Jane”} = 48;
Other techniques • Adding an entry: $grades{“Jill”} = 75; • Deleting an entry delete $grades{“Jill”}; • Does an entry exist? if exists($grades{“Jill”}) { print “Jill is in the class.\n”; }
Getting keys/values • Getting the list of all keys @students = keys(%grades); • Getting the list of all values @grades = values(%grades);
What’s the average grade? $num_students = $#students + 1; $total_points = 0; foreach $grade (@grades) { $total_points += $grade; } $avg = $total_points / $num_students; print “The class mean is $avg\n”;
HTML Forms • All widgets are contained in the <form> tag. <form action=“url” method=“post”> … </form>
Widgets • Buttons: submit, reset, action • Text: input, text areas, passwords • Selectors: check, radio, lists • Hidden fields • Each widget (or group) is transmitted as a name/value pair to the server.
Buttons • Basic syntax <input type=“type” value=“value” name=“name”> • submit, reset, or button specified by type • text appearing on the button given by value • can have multiple submit buttons by naming each one
Getting text <input type=“text” size=“”, maxlength=“”, name=“”> • Allows user to enter a line of text up to maxlength • Set type to password to use asterisks • not secure
Text areas <textarea rows=“” cols=“” name=“”> • Allows free-form entry spanning multiple lines • Comments, input on NSF, conference registration sites
Radio buttons • A group of several buttons, of which at most one may be checked <input type=“radio” name=“foo” value=“a”> a <input type=“radio” name=“foo” value=“b”> b • All have same name • Can specify a default value by setting one to be checked
Check boxes • Group with same name, several can be checked <input type=“checkbox” name=“foo” value=“a”> a <input type=“checkbox” name=“foo” value=“b”> b • Multiple values sent as a list
Selection lists <select name=“states” size=“5”> <option> AL <option> AK <option> AR … </select> • gives one value • can set one option to be selected • can also allow multiple items
Hidden fields <input type=“hidden” name=“foo” value=“bar”> • In multi-form applications, passes information from one page to the next
Common Gateway Interface • A standard for interfacing external applications with information servers • Not a particular language, but a rule for passing information • Many languages provide a module/library for handling this automagically.
The Perl/CGI module use CGI ‘:standard’; • gives access to lots of functions, pre-defined strings • also gives parameter-passing tools
Example of code generation #!/usr/local/bin/perl use CGI ‘:standard’; print header; print start_html({-title=>’Hello’, bgcolor=>“pink”}); print p(“Hello world”); print end_html;
Getting data from forms • Set the action of a form to some perl script • Write the Perl script • use the param() function to get the value of the form items • Example: piping survey
Testing scripts • Command-line mode: perl myprog.pl name=value • Passing arguments via URL: http://<path>/myprog.pl?name=value
Environment variables • When Perl is started from a browser, a special hash list is created describing how it was invoked. This is called the environmental hash list and is called %ENV • Referring Web site, what browser, language, method, remote address, remote host
Environment variables HTTP_REFERRER, REQUEST_USER_AGENT, HTTP_ACCEPT_LANGUAGE, REQUEST_METHOD, REMOTE_ADDRESS, REMOTE_HOST • Can configure response to browser or disallow/ allow certain domains
What next? • Scripts to write the forms • Scripts to validate the form and spit it back if the user didn’t enter everything correctly • Example: newform.pl
Files • Files are opened via the open command: open(FILE,’filename’); • First argument is the “handle” • Similar to FILE* in C • Second argument is a string -- the name of the file (perhaps including path)
Options for opening files • Read (default): open(HANDLE,’<filename’); • Write: open(HANDLE,’>filename’); • Append open(HANDLE,’>>filename’); • Uses redirection operators from Unix
What about errors? • Errors can occur if a file that doesn’t exist is opened for reading, etc open(HANDLE,’<filename’) || die “Can’t open file $!”; • sends error message to STDERR • The variable $! contains the latest error message returned by a system call • open returns 0 or 1
Reading from files (and STDIN) • Use the syntax <HANDLE> to get either a line or the whole file $aline = <MYFILE>; @lines = <MYFILE>; • By not specifying a location, the line of input appears in $_.
Example • To read in a whole file and print it back to the screen, we use the code open(FILE,’filename’) || die $!; while(<FILE>) { print $_; } close FILE; • An EOF is interpreted as false in the loop
Even more arcane open(FILE,’filename’) || die $!; while(<FILE>) { print; } close FILE; • The default argument of print (and some other functions) is $_.
More implicit variables • Records in a file (normally lines) are separated by $/ • changing this from “\n” to “” reads in paragraph mode, to “undef();” reads in the whole file • Output field separator: $, • print “one”, “two” equivalent to • print “one” . $, . “two • Output record separator: $\ • Typically blank • Changing it changes the terminal value of print statements
Example • Read and print email addresses • Read, sort, and print email addresses • Read and print links to email addresses
Editing a file • Open file for reading • Read everything into memory • Close the file • Make the changes (in memory) • Open the file for writing • Write the file • Close the file