Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Programming the WWW I CMSC 10100-1 Winter 2003.

Similar presentations


Presentation on theme: "Introduction to Programming the WWW I CMSC 10100-1 Winter 2003."— Presentation transcript:

1 Introduction to Programming the WWW I CMSC 10100-1 Winter 2003

2 A Crash Course in Perl Variables: –scalar, array, hash HTML forms CGI Files -- reading and writing

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

4 Scalar variables For numerical values, we can add, subtract, multiply, divide, assign as in Javascript: $x = 42; $y = 63; $z = $x + $y - 32;

5 String variables $foo=“Hello world”; $bar=“I’m joining the circus”; String concatentation: $foo. $bar String repitition: $foo x 3

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

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

8 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’);

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

10 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);

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

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

13 Getting keys/values Getting the list of all keys @students = keys(%grades); Getting the list of all values @grades = values(%grades);

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

15 HTML Forms All widgets are contained in the tag. …

16 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.

17 Buttons Basic syntax submit, reset, or button specified by type text appearing on the button given by value can have multiple submit buttons by naming each one

18 Getting text Allows user to enter a line of text up to maxlength Set type to password to use asterisks –not secure

19 Text areas Allows free-form entry spanning multiple lines Comments, input on NSF, conference registration sites

20 Radio buttons A group of several buttons, of which at most one may be checked a b All have same name Can specify a default value by setting one to be checked

21 Check boxes Group with same name, several can be checked a b Multiple values sent as a list

22 Selection lists AL AK AR … gives one value can set one option to be selected can also allow multiple items

23 Hidden fields In multi-form applications, passes information from one page to the next

24 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.

25 The Perl/CGI module use CGI ‘:standard’; gives access to lots of functions, pre- defined strings also gives parameter-passing tools

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

27 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

28 Testing scripts Command-line mode: perl myprog.pl name=value Passing arguments via URL: http:// /myprog.pl?name=value

29 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

30 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

31 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

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

33 Options for opening files Read (default): open(HANDLE,’<filename’); Write: open(HANDLE,’>filename’); Append open(HANDLE,’>>filename’); Uses redirection operators from Unix

34 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

35 Reading from files (and STDIN) Use the syntax to get either a line or the whole file $aline = ; @lines = ; By not specifying a location, the line of input appears in $_.

36 Example To read in a whole file and print it back to the screen, we use the code open(FILE,’filename’) || die $!; while( ) { print $_; } close FILE; An EOF is interpreted as false in the loop

37 Even more arcane open(FILE,’filename’) || die $!; while( ) { print; } close FILE; The default argument of print (and some other functions) is $_.

38 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

39 Example Read and print email addresses Read, sort, and print email addresses Read and print links to email addresses

40 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


Download ppt "Introduction to Programming the WWW I CMSC 10100-1 Winter 2003."

Similar presentations


Ads by Google