2 html cgi perl

67 %
33 %
Information about 2 html cgi perl

Published on November 6, 2007

Author: george

Source: authorstream.com

The Web:  The Web Computer networks link your machine to computers throughout the world Internet global network of computers no one owns or controls the whole thing 30-40 million people have access Your machine Campus Network The Internet The Web:  The Web www - big library site - book in library page - page in book home page - cover page/toc hyperlink: page connector …… …… …… …… …… …… …… …… …… …… WWW - graphical, easy-to-navigate interface pages, links: form web of info How does it work?:  How does it work? Browser: software to look at web pages (Netscape Navigator) Server: software that provides service The client (Web browser) on your machine sends a request to a server. The server sends the file requested by the browser. The file contains data and formatting information The browser displays the file on the screen. Your machine The Internet Web browser Page Location Web server Uniform Resource Locator (URL):  Uniform Resource Locator (URL) Every page has a unique address (URL) domain/directories/filename.ext The URL for SCU is: www.scu.edu The Web page for this course is: www.cse.scu.edu/~lseiter/coen176/index.html HTML Document: www.ncsa.uiuc.edu/General/Internet/WWW/HTMLPrimerAll.html A good quick reference: kuhttp.cc.ukans.edu/info/HTML_quick.html Bare bones guide to HTML werbach.com/barebones/barebone_table.html HTML:  HTML HTML stands for HyperText Markup Language. Structural vs. Physical Markup PLAIN TEXT FILES: can use with any editor. Basic idea: Insert embedded commands (tags) into text files to tell the browser how to format the related text and where to put an image and where to find an image file. Data is transferred between the browser and the server in http (hypertext transfer protocol). http://www.cse.scu.edu/index.html The quickest way to start: When you see a nicely designed page and wonder how it is done, select "view->document source" in Netscape to see the source code. You can save the document in your file sys. Copying html file and creating your own from it is ok. Copying someone else's image may not be ok. The Basic Format:  The Basic Format An HTML element: basic component of structure of a text document (head, table, list, etc.) Mark element with a tag, tells browser how to display element. Element: may include a name, some attributes and some text or hypertext, and will appear in an HTML document as <tag_name> text </tag_name> , <tag_name attribute_name=argument> text </tag_name>, or just <tag_name> For example: <title> My Useful Document </title> <img src=“smile.gif”> The Basic Format:  The Basic Format An HTML document is composed of a single element: <html> . . . </html> that is, in turn, composed of head and body elements: <head> .. <title> …</title> . . </head> and <body> . . . </body> html, body, and head are optional. html tag: tells browser the file is html encoded. should name files .html Header section:  Header section Header: contains info about the document <title> . . . </title> Specify a document title. Note that the title will not appear on the document as is customary on printed documents. It will usually appear in a window bar identifying the contents of the window. HTML header tags perform the functions usually reserved for titles. title also used in hotlists, bookmarks. should be descriptive, short prologue, meta, and lots of other header tags Body element (Text Elt.):  Body element (Text Elt.) Second part of document, contains primary content Headings: six levels of text sizing (h1, h2, … h6) Paragraphs: <p> don’t need end tag <p align = center> This is centered, need end tag </p> The end of a paragraph that will be formatted before it is displayed on the screen. <pre> . . . </pre> Identifies text that has already been pre formatted by some other system and must be displayed as is. Preformatted text may include embedded tags, but not all tag types are permitted. The <pre> tag can be used to include tables in documents. <xmp> . . . </xmp> Similar to <pre> except no embedded tags will be recognized. <plaintext>: Similar to <pre> except no embedded tags will be recognized, and since there is no end tag, the remainder of the document will be rendered as plain text. This is an archaic tag. Note that some browsers actually recognize a </plaintext> tag, even though it is not defined by the standard. <blockquote> . . . </blockquote> Include a section of text quoted from some other source. A Simple Example:  A Simple Example Example: <html> <head> <TITLE>A Simple HTML Example</TITLE> </head> <body> <H1>HTML is Easy To Learn</H1> <P>Welcome to the world of HTML. This is the first paragraph. While short it is still a paragraph!</P> <P>And this is the second paragraph.</P> This also works <P> This is to break a line without <br> starting a new paragraph </body> </html> Styles:  Styles Headers <h1> ... </h1>Most prominent header <h2> ... </h2> …. <h6> ... </h6>Least prominent header Physical Styles <b> . . . </b> Boldface <i> . . . </i> Italics <u> . . . </u> Underline <tt> . . . </tt> Typewriter font Definition list/glossary: <dl> <dl> <dt> First term to be defined <dd> Definition of first term <dt> Next term to be defined <dd> Next definition </dl> Example: </dl> <dt>Item1 <dd>Good guy <dt>Item2 <dd>Bad guy </dl> Ouput: Item1 Good guy Item2 Bad guy When use <dl compact> the item heading and the text go to the same line. Slide12:  Present an unordered list: <ul> <ul> <li> First item in the list <li> Next item in the list </ul> Present an ordered list: <ol> <ol> <li> First item in the list <li> Next item in the list </ol> Nested list: You can nest lists Excample <UL> <LI> California <LI> Florida </UL> <OL> <LI> California <LI> Florida </OL> <UL> <LI> A few New England states: <UL> <LI> Vermont <LI> New Hampshire <LI> Maine </UL> <LI> Two Midwestern states: <UL> <LI> Michigan <LI> Indiana </UL> </UL> California Florida 1. California 2. Florida A few New England states: Vermont New Hampshire Maine Two Midwestern states: Michigan Indiana Logical Styles:  Logical Styles <DFN> for a word being defined. Typically displayed in italics. (NCSA Mosaic is a World Wide Web browser.) <EM> for emphasis. Typically displayed in italics. (Consultants cannot reset your password unless you call the help line.) <CITE> for titles of books, films, etc. Typically displayed in italics. (A Beginner's Guide to HTML) <CODE> for computer code. Displayed in a fixed-width font. (The <stdio.h> header file) <KBD> for user keyboard entry. Typically displayed in plain fixed-width font. (Enter passwd to change your password.) <SAMP> for a sequence of literal characters. Displayed in a fixed-width font. (Segmentation fault: Core dumped.) <STRONG> for strong emphasis. Typically displayed in bold. (NOTE: Always check your links.) <VAR> for a variable, where you will replace the variable with specific information. Typically displayed in italics. (rm filename deletes the file.) Links and Anchors:  Links and Anchors LINK TEXT AND/OR IMAGE TO ANOTHER DOCUMENT <a> anchor (hypertext tag) <a name="anchor_name"> . . . </a> Define a target location in a document It is often used without </a>w <a href="#anchor_name"> . . . </a> Link to a location in the same document <a href="URL"> . . . </a> Link to another file/resource <a href=“http://www.site.domain/dir/file.html”> <a href="URL#anchor_name"> . . . </a> Link to a target location in another document <a href="URL?search_word+search_word"> . . . </a> Send a search string to a server. Different servers may interpret the search string differently. In the case of word-oriented search engines, multiple search words might be specified by separating individual words with a plus sign (+). The structure of a Uniform Resource Locator (URL) may be expressed as: resource_type:additional_information where the possible resource types include: file, http, news, gopher, telnet, ftp, and wais, among others, and each resource type relates to a specific server type. Misc.:  Misc. <!-- text --> Place a comment in the HTML source <img src="URL" alt="Alternate Text"> Embed a graphic image in the document. Attributes: src : Specifies the location of the image. alt : Put a text str to be in place of the image in clients that cannot display images. align : Specify a relationship to surrounding text. The argument for align can be one of top, middle, or bottom. ismap : If ismap is present and the image tag is within an anchor, the image will become a "clickable image". The pixel coordinates of the cursor will be appended to the URLspecified in the anchor if the user clicks within the ismap image. The resulting URL will take the form "URL?m,n" where m and n are integer coordinates, and the URL will specify the location of a program that will examine the pixel coordinates, and return an appropriate document. <br> Forces a line break immediately and retains the same style. <hr> Places a horizontal rule or separator between sections of text. CGI Programming:  CGI Programming Forms :  Forms forms enable two-way flow of info data can be gathered by a CGI script and saved <form method=“post” action=“mailto:fred@scu.edu”>form text </form> <form method=“get” action=“URLofSCRIPT”> form text </form> <form method=“post” action=“URLofSCRIPT”> form text </form> single line input (text, checkbox,radio,etc) multi line input (text) drop-down menus Forms :  Forms form> . . . </form> : Define a form <input> : an input box Attributes (type, name, value, checked, size, maxlength): type="variable_type" Specifies the data type for the variable type="text" fields accept character data (default) type="password" fields accept character data type="checkbox" fields are either selected or not type="radio" fields of same name allow selection of only one of the associated values type="submit" defines an action button that sends completed form to the query server type="reset" defines a button that resets the form variables to their default values type="hidden" defines invisible input field, value sent along with the other form values. (pass internal-state values) Forms :  Forms Attributes: name="textstring" where textstring is a symbolic name (not displayed) identifying input variable as in: <input type="checkbox" name="box1"> value="textstring” meaning of textstring depends on type. If type="text" or type="password", textstring is default value for input variable. If type="checkbox" or type="radio", textstring is value sent to server if checkbox "checked". If type="reset" or type="submit”, textstring is button label (in place of words "submit" and "reset”). Forms:  Forms checked No arguments. For type="checkbox" or type="radio", if checked is present the input field is "checked"by default. size="display_width" where display_width is an integer value representing the number of characters displayed for type="text" or type="password". maxlength="string_length" where string_length is the maximum number of characters allowed within type="text" or type="password" variable values. This attribute is only valid for single line "text" or "password" fields. <select> . . . </select> <select> <option>Apples <option selected>Bananas <option>Cherries </select> <textarea> ... default text </textarea> Defines a rectangular field where the user may enter text data name="textstring" rows="num_rows" cols="numcols" CGI Programming:  CGI Programming CGI: Common Gateway Interface A simple protocol to communicate between web forms and your program. CGI descriptions: http://hoohoo.ncsa.uiuc.edu/cgi/ Quick tutorial: http://www.jmarshall.com/easy/cgi/ CGI program can be written in any language that can read from STDIN, write to STDOUT, and access environment variables. e.g., C, Perl, Java, Shell. Typical programming pattern: 1. Read input data from STDIN 2. Processing the data 3. Write the HTML response to STDOUT. When a user submit a form, the sequence of variables are sent to the server in the following format: "name1=value1&name2=value2&name3=value3" Standard CGI script input processing: 1. Split the string by "=" and "&” 2. Convert all "+" characters to spaces, and 3. Convert all "%xx" sequences to the single character whose ascii value is "xx", in hex. For example, convert "%3d" to "=". You can find input processing funcs in C, Perl, etc on the web. CGI Programming:  CGI Programming When the http server receives a submission, depending on the submission method of the form, the server construct environment variables and call the CGI program specified by the form. For POST method, the long string can be obtained by reading from STDIN. String length is in environment variable CONTENT_LENGTH. For GET method, the string is in QUERY_STRING GET has length limit. POST is more popular. Sending HTML response back to user: just write to STDOUT The first line should be: Content-Type: text/html Then write the rest of your HTML contents. You can send other type of data back to use, such as "Content-type: image/gif" followed by binary gif file data. Not all browers support all data types. Sending an existing file to the user as response. Write the following to STDOUT Location: response.html -- followed by a blank line. TEST.HTML:  TEST.HTML <TITLE> TESTING FORMS </TITLE> </HEAD> <FORM METHOD=”post" ACTION="http://www.scu.edu/~fred/cgi-bin/testpost.cgi"> First entry field: <INPUT NAME="entry1"> <BR> Second entry field: <INPUT NAME="entry2" VALUE="bloop"> <BR> Third entry field: <INPUT NAME="entry3"> --- Select Option: <SELECT NAME="entry4"> <OPTION VALUE="no1">A <OPTION VALUE="no2">B <OPTION VALUE="no3">C <OPTION VALUE="no4">D </SELECT> <p> To submit the query, press: <INPUT TYPE="submit" VALUE="Submit Query">. <P> </FORM> </BODY> </HTML> TESTPOST.CGI :  TESTPOST.CGI #!/bin/sh echo “Content-Type: text/html \n” echo “<title> forms support test server </title><body> This script executed at `date`, on receipt of the form you sent. The form included the following arguments:<hr>” cat echo “</body>” WHAT DOES THIS DO? Translating &,= :  Translating &,= #!/bin/sh echo “Content-Type: text/html \n” echo “<title> forms support test server </title><body> This script executed at `date`, on receipt of the form you sent. The form included the following arguments:<hr>” tr ‘&=‘ ‘\012 ‘ echo “</body>” WHY DOESN’T THIS WORK? Translating &,= :  Translating &,= #!/bin/sh echo “Content-Type: text/html \n” echo “<title> forms support test server </title><body> This script executed at `date`, on receipt of the form you sent. The form included the following arguments:<hr>” tr ‘&=‘ ‘\012 ‘ | awk ‘ { print $1 “ “ $2 “<br>” } ‘ echo “</body>” PERL -- Practical Extraction and Report Language:  PERL -- Practical Extraction and Report Language Introduction:  Introduction Perl is an interpreted language for scanning files, extracting information from those text files, and printing reports based on that information. Perl is mainly used to handle text files, but can be used for binary files (databases), process manipulation, network tasks. (Practically everthing really likeable about shells,awk,sed,grep,C) Runs on DOS and UNIX Expresion syntax is very similar to that of C. There are translators that translate sed and awk into Perl script. Perl does not arbitrarily impose limit on data structures. Strings have unlimited length. Recursion is of unlimited depth. Information source: http://www.perl.com/perl/faq/, http://www.phlab.missouri.edu/cgi-bin/perlman A simple example:  A simple example perl -e ‘print “hello dolly\n”;’ hello dolly "-e" is followed by Perl command (execute command line instead of reading from a script file). Unlike sed and awk, where a sequence of commands is executed for each line of input, Perl executes each command just once. Use the -n option to implicitly loop over a file, or use an explicit loop to iterate the file. Another simple example:  Another simple example $cat foo this is the first line second line $perl -ne ‘print’ foo -n option is used to implicitly loop through the file a line at a time. this is the first line second line $perl -ne ‘print if /^this/’ foo this is the first line $date | perl -ne ‘print “Today is $_” $_ is a variable referring to input Today is October 15, 1997 A Simple Script - foo.perl:  A Simple Script - foo.perl #!/usr/contrib/bin/perl -w #This is a comment line print “Hello\n” $ perl -c foo.perl foo.perl syntax ok $foo.perl #This is a comment line print “Hello\n” $perl foo.perl Perl IO:  Perl IO PERL works with stdin, stdout, stderr, but does not access the streams directly Filehandles: STDIN, STDOUT, STDERR Printing output: any unknown word (not a filehandle, label, reserved word) is treated as if surrounded by single quotes perl words ARE case sensitive single quotes - all characters treated as literals double quotes - all chars literal except variable substitution, escape sequences \t tab \n newline \\ backslash special literals (should not be double quoted) _LINE_ current line number _FILE_ current filename Perl IO (scripts):  Perl IO (scripts) print “Hello”, “world”, “\n”; HelloWorld print “Hello world\n”; Hello world print Hello, world,”\n”; no comma allowed after filehandle (ERROR: filehandle must be specified when literals not quoted) print STDOUT Hello, world,”\n”; Helloworld Perl IO (scripts):  Perl IO (scripts) print “The price is $100.\n” The price is . (looks for scalar variable $100) print “The price is \$100.\n” The price is $100. print “The price is $”,100,”.\n” The price is $100 print “The number is “,0777,”.\n” (octal due to leading 0) The number is 511 print “The number is “,0xAbcF,”.\n” (hex due to leading 0x) The number is 43983 print “The unformatted number is “,14.56,”.\n” (use default format) The unformatted number is 14.5600000. print “***\tIn double quotes\t***\n” *** In double quotes *** print ‘***\tIn single quotes\t***\n’ ***\tIn single quotes\t***\n print “Current line number is “,_LINE,”\n” (interpret, literal not in quotes) Current line number is 7 Printf:  Printf printf - print formatted string printf(“The name is %s and the number is $d\n”,”John”,50); The name is John and the number is 50 c - character s - string d - decimal x - hex o - octal e - floating point, scientific notation f - floating point 3 types of Perl variables:  3 types of Perl variables Scalars can be numeric or character as determined by context: 123 12.4 5E-10 0xff (hex) 0377 (octal) 'What you $see is (almost) what \n you get' 'Don\'t Walk' "How are you?" "Substitute values of $x and \n in \" quotes." `date` `uptime -u` `du -sk $filespec | sort -n` $x $list_of_things[5] $lookup{'key'} Double-quotes allow substitution of variables and control codes. Back-quotes also allow substitution, then try to execute the result as a system command, returning as the final value whatever the system command outputs. Arrays of scalars (also called lists) are sequentially-arranged scalars: @dow=('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday') (13,14,15,16,17,18,19) equivalent to (13..19) (13,14,15,16,17,18,19)[2..4] equivalent to (15,16,17) @whole_list # the entire array Associative arrays (also called hashes) facilitate arbitrary recall: %states=(‘CA’,’California’,’ME’,’Maine’,….) $states{‘ME’} Example:  Example $salary = 5000; @months = (Mar, Apr, May); %states =(‘CA’,’California’,’ME’,’Maine’,’MT’,’Montana’); print “$salary\n” print “@months\n” print “$months[0]\n” print “$states{‘CA’}\n” print $x + 3,”\n” #x initialized to 0 since context is numeric print “***$name***\n” #name initialized to empty string due to context 5000 Mar Apr May Mar California 3 ******* Name Convention:  Name Convention Scalar variables start with '$', even when referring to an array element. The variable name reference for a whole list starts with '@', and the variable name reference for a whole associative array starts with '%'. Lists are indexed with square brackets enclosing a number, normally starting with [0]. In Perl 5, negative subscripts count from the end. Thus, $things[5] is the 6th element of array @things, and ('Sun','Mon','Tue','Wed','Thu','Fri','Sat')[1] equals 'Mon'. Associative arrays are indexed with curly brackets enclosing a string. $whatever, @whatever, and %whatever are three different variables. Examples @days = (31,28,31,30,31,30,31,31,30,31,30,31); # A list with 12 elements. $#days # Last index of @days; 11 for above list $#days = 7; # shortens or lengthens list @days to 8 elements @days # ($days[0], $days[1],... ) @days[3,4,5] # = (30,31,30) @days{'a','c'} # same as ($days{'a'},$days{'c'}) %days # (key1, value1, key2, value2, ...) Case is significant--"$FOO", "$Foo" and "$foo" are all different variables. If a letter or underscore is the first character after the $, @, or %, the rest of the name may also contain digits and underscores. If this character is a digit, the rest must be digits. Name Convention (Conti.):  Name Convention (Conti.) Perl has several dozen special variables whose second character is non-alphanumeric. For example, $/ is the input record separator, newline "\n" by default. An uninitialized variable has a special "undefined" value which can be detected by the function defined(). Undefined values convert depending on context to 0, null, or false. The variable "$_" Perl presumes when needed variables are not specified. Thus: <STDIN>; assigns a record from filehandle STDIN to $_ print; prints the curent value of $_ chop; removes the last character from $_ @things = split; parses $_ into white-space delimited words, which become successive elements of list @things. -- Use with CARE Subroutines and functions are referenced with an initial '&', which is optional if reference is obviously a subroutine or function such as following the sub, do, and sort directives: sub square { return $_[0] ** 2; } print "5 squared is ", &square(5); Filehandles don't start with a special character, and so as to not conflict with reserved words are most reliably specified as uppercase names: INPUT, OUTPUT, STDIN, STDOUT, STDERR, etc. Number and Characters:  Number and Characters Example: #!/usr/local/bin/perl print '007',' has been portrayed by at least ', 004, ' actors. '; print 7+3, ' ', 7*3, ' ', 7/3, ' ', 7%3, ' ', 7**3, ' '; $x = 7; print $x; print ' Doesn\'t resolve variables like $x and backslashes \n. '; print "Does resolve $x and backslash\n"; $y = "A line containing $x and ending with line feed.\n"; print $y; $y = "Con" . "cat" . "enation!\n"; print $y; This produces: 007 has been portrayed by at least 4 actors. 10 21 2.3333333333333335 1 343 7 Doesn't resolve variables like $x and backslashes \n. Does resolve 7 and backslash A line containing 7 and ending with line feed. Concatenation! Another Example:  Another Example #!/usr/contrib/bin/perl -w if ($#ARGV >= 0) # $ indicate scalar var # #ARGV is a special var -- the index of the last entry # in the argument array. ( # of arguments - 1) { $who = join(' ', @ARGV); } # @ indicates array. join() all elements # the array into a string with the given delimiter else { $who = 'World'; } print "Hello, $who!\n"; # print to stdout. Substitution Example:  Substitution Example Perl One-Liner That Substitutes Text In Multiple File perl -e 's/gopher/World Wide Web/gi' -p -i.bak *.html "-e" is followed by Perl command (execute command line instead of reading from a script file). "s"substitutes for the phrase "gopher" the phrase "World Wide Web"; "g" is global across each line, "i" turn off case sensitiveity. "-i" with an exension will make a copy of the file with the name <orig. filenme>.<extension given> "-p" cause the command to loop through the files line by line Substitution Example:  Substitution Example The same thing can be done by the following Perl program. If the file is named x.perl, either "perl x.perl" or "x.perl" will run the perl program. #!/usr/local/bin/perl -w # the option -w causes Perl to produce warnings for misuse of keywords … # This Perl program in classic programming style changes the string "gopher" to # "World Wide Web" in all files specified on the command line. $original='gopher'; # "$" refers to a singular variable $replacement="World Wide Web"; # both ' and " work for string literals $nchanges = 0; # The input record separator is defined by Perl global variable $/. It can be anything, # including multiple characters. Normally it is "\n", newline. Here, we say there is # no record separator, so the whole file is read as one long record, newlines included. undefine $/; Substitution Example (conti.):  Substitution Example (conti.) for ($i=0; $i <= $#ARGV; $i++) { # familiar for loop syntax. #ARGV is the index # of the last entry in ARGV[]. $file = $ARGV[$i]; # get next argument as file name if (! open(INPUT,"<$file") ) { # open input file "<" for input, ">" for output # return nonzero if successful print STDERR "Can't open input file $bakfile\n"; # STDERR is standard error next; # terminate the current iteration of the innermost enclosing loop } $data=<INPUT>; # Read input file as one long record. close INPUT; Substitution Example (conti.):  Substitution Example (conti.) if ($data =~ s/$original/$replacement/gi) { # if any match is found $bakfile = "$file.bak"; # get backup file name if (! rename($file,$bakfile)) { # Abort if can't backup original or output. die "Can't rename $file $!"; } # print the error message and quit if (! open(OUTPUT,">$file") ) { # open the output file die "Can't open output file $file\n"; } print OUTPUT $data; # write the result into the file close OUTPUT; print STDERR "$file changed\n"; $nchanges++; } else { print STDERR "$file not changed\n"; } } print STDERR "$nchanges files changed.\n"; exit(0); Expression Can Be Confusing:  Expression Can Be Confusing The same expression can be written in many different ways in Perl. The following lines mean the same thing: if ($x == 0) {$y = 10;} else {$y = 20;} $y = $x==0 ? 10 : 20; $y = 20; $y = 10 if $x==0; unless ($x == 0) {$y=20} else {$y=10} if ($x) {$y=20} else {$y=10} $y = (10, 20)[$x != 0]; Comparison:  Comparison # The following "<<" variation of # data input simplifies CGI forms. $x = 'operator'; print <<THATSALL; Hello THATSALL $x = 7; if ($x == 7) { print "x is $x\n"; } if ($x = 5) { print "x is now $x,", "the assignment is successful.\n";} $x = 'stuff'; if ($x eq 'stuff') { print "Use eq, ne, lt, gt, etc for strings.\n"; } This produces: Hello x is 7 x is now 5, the assignment is successful. Use eq, ne, lt, gt, etc for strings. Ordinary Arrays:  Ordinary Arrays Example: @stuff = ('This', 'is', 'a', 'list.'); print "Lists and strings are indexed from 0.\n"; print "So \$stuff[1] = $stuff[1], ", "and \$#stuff = $#stuff.\n"; print @stuff,"\n"; print join('...',@stuff),"\n"; splice(@stuff, 3, 0, ('fine', 'little')); # replace 0 elements from index 3 by 'fine'... print join('...',@stuff),"\n"; This produces: Lists and strings are indexed from 0. So $stuff[1] = is, and $#stuff = 3. Thisisalist. This...is...a...list. This...is...a...fine...little...list. Command line value and loops:  Command line value and loops Example: print "$#ARGV is the subscript of the ", "last command arg.\n"; # Iterate on numeric subscript 0 to $#ARGV: for ($i=0; $i <= $#ARGV; $i++) { print "Argument $i is $ARGV[$i].\n"; } # A variation on the preceding loop: foreach $item (@ARGV) { print "The word is: $item.\n"; } # A similar variation, using the # "Default Scalar Variable" $_ : foreach (@ARGV) { print "Say: $_.\n"; } Demonstration: > perl example5.pl Gooood morning, Class! 2 is the subscript of the last command arg. Argument 0 is Gooood. Argument 1 is morning,. Argument 2 is Class!. The word is: Gooood. The word is: morning,. The word is: Class!. Say: Gooood. Say: morning,. Say: Class!. Printf:  Printf Print a formatted strong to a selected file handle (STDOUT) Like printf() in C language printf(FILEHANDLE FORMAT, LIST); printf(FORMAT, LIST); printf(“The number is %s and the number is %d”,”John”, 345); Stdin :  Stdin Perl uses <> input (read) operator get a line from the FILEHANDLE we can use chop to remove the newline \n Examples print “What is your name?” $name = <STDIN>; #enclose STDIN with input operator print “What is your age?” $age = <>; #read using input operator chop ($name); #remove the \n from the string Read multiple inputs into arrays @all = <STDIN>; getc :  getc Gets a single character into a string from a file or STDIN getc(FILEHANDLE); getc FILEHANDLE; getc Examples: print “Answer y or n”; $answer = getc; printf(“You say %s\n”,$answer); argv[] :  argv[] @ARGV is the argument array #!/usr/bin/perl printf(“Number of args %d\n”,$#ARGV+1); print “@ARGV\n”; $a = $ARGV[0]; $b = $ARGV[1]; $c = $ARGV[2]; printf(“The name of the scripts is %s\n”,$0) printf(“Argument: %s %s %s\n”,$a,$b,$c); Array Functions :  Array Functions chop(LIST) chops off last char of each string in the list pop(ARRAY) pops off last element of the array push(ARRAY,X) similar to stack operation join(DELIMITER, LIST) joins the elements of the array into a single string and separates each one by the delimiter split(DELIMITER,EXP) splits up a string by some delimiter and returns an array Special Arrays :  Special Arrays The %ENV contains environment variables the key is the name of the environment variable the value is what is assigned to it Example: foreach $key (keys(%ENV)) { print”$key\n”; } print “Your login name $ENV{‘LOGNAME’}\n”; $pwd = $ENV{‘PWD’}; print $pwd; Operators :  Operators Most of the operators are borrowed from C Mixing data types $x = “ 12!!” + “4\n”; #strings are converted into a number print “$x”; $y = ZAP . 5.5; #concatenate two strings Output: 16 ZAP5.5 Perl tests whether operator expects string or number. If numeric operator, then perl converts string to floating point value. Leading whitespace or trailing non-numeric characters, they will be ignored. Converts to zero if it can’t figure out what to do. Operators :  Operators Assignment operators =,+=,-=,<<=,… Relational operators numeric: >,>=,<,<=,==,!=,<=> string: gt,ge,lt,le,eq,ne,cmp Logical operators &&,||,! $x ? $y : $z String operators and functions $s1 . $s2 $s1 x $num substr($str1,$offset,$len) length(EXPR) index($str1,$str2) Conditional Constructs :  Conditional Constructs if (expr) {block} if (expr) {block} else {block} if (expr) {block} elseif (expr) {block} else {block} unless (expr) {block} unless (expr) {block} else {block} unless (expr) {block} elseif (expr) {block} …. while (expr) {block} eval expr before executing block until (expr) {block} do {block} while (expr); eval expr after executing block do {block} until (expr); Loops :  Loops for (expr1; exp2; exp3){block} foreach var (array) {block} $_ used if var is not present @color=(red, green, blue); foreach (@color) { print “$_”; $_ = black; } print “\n@color” red green blue black black black Standard I/O:  Standard I/O print STDOUT "Tell me something: "; while ($input = <STDIN>) { print STDOUT "You said, quote: $input endquote\n"; chop $input; print STDOUT "Without the newline: $input endquote\n"; if ($input eq '') { print STDERR "Null input!\n"; } print STDOUT "Tell me more, or ^D to end:\n"; } print STDOUT "That's all!\n"; Note 1: The while statement's condition is an assignment statement: assign the next record from standard input to the variable $input. On end of file, this will assign not a null value but an "undefined" value. An undefined value in the context of a condition evaluates to "false". Note 2: Data records are by default terminated by a newline character "\n" which in the above example is included as the last character of variable $input. The "chop" function removes the last character of its argument. Perl 5 introduces a "chomp" function that removes the last characters of a variable only if they are the currently defined end-of-record sequence, which is defined in the special variable $/. File I/O:  File I/O #!/usr/local/bin/perl # Function: Reverse each line of a file # 1: Get command line values: if ($#ARGV !=1) { die "Usage: $0 inputfile outputfile\n";} ($infile,$outfile) = @ARGV; if (! -r $infile) { die "Can't read input $infile\n";} if (! -f $infile) { die "Input $infile is not a plain file\n";} # 2: Validate files # Or statements "||" short-circuit, so that # if an early part evaluates as true, Perl # doesn't bother to evaluate the rest. # Here, if the file opens successfully, # we don't abort: open(INPUT,"<$infile") || die "Can't input $infile $!"; if ( -e $outfile) { print STDERR "$outfile exists!\n"; until ($ans eq 'r' ||$ans eq 'a'||$ans eq 'e' ){ print STDERR "rplc, append,or exit? "; $ans = getc(STDIN); } if ($ans eq 'e') {exit} } if ($ans eq 'a') {$mode='>>'} else {$mode='>'} open(OUTPUT,"$mode$outfile") || die "Can't output $outfile $!"; # 3: read & reverse each line, output it. while (<INPUT>) { chop $_; $_ = reverse $_; print OUTPUT $_,"\n"; } # 4: Done! close INPUT,OUTPUT; exit; Pipe I/O and System Calls:  Pipe I/O and System Calls #!/usr/local/bin/perl # Report on disk usage under specified files # The Unix command "du -sk ..." (on BSD Unix, "du -s ...") # produces a series of lines: # 1942 bin # 2981 etc # … # listing the K bytes used under each file or directory. It doesn't show other # information, such as the modification date or owner. This program gets du's kbytes # and filename, and merges this info with other useful information for each file. $files = join(' ',@ARGV); # The trailing pipe "|" directs command output into our program: if (! open (DUPIPE,"du -sk $files | sort -nr |")) { die "Can't run du! $!\n"; } printf "%8s %-8s %-16s %8s %s\n", 'K-bytes','Login','Name','Modified','File'; while (<DUPIPE>) { # parse the du info: ($kbytes, $filename) = split; # Call system to look up file info like "ls" does: ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev, $size,$atime,$mtime,$ctime) = stat($filename); Pipe I/O and System Calls (conti.):  Pipe I/O and System Calls (conti.) # Call system to associate login & name with uid: if ($uid != $previous_uid) { ($login,$passwd,$uid,$gid,$quota,$comment,$realname,$dir,$shell) = getpwuid($uid); $realname) = split(',',substr($realname,0,20)); $previous_uid = $uid; } # Convert the modification-time to readable form: ($sec,$min,$hour,$mday,$mon,$myear) = localtime($mtime); $mmonth = $mon+1; printf "%8s %-8s %-16s %02s-%02d-%02d %s\n", $kbytes, $login, $realname, $myear, $mmonth, $mday, $filename; } # while loop Demonstration Output K-bytes Login Name Modified File 40788 c527100 Fred Flintstone 95-10-05 c527100 32685 c565060 Peter Parker 95-10-05 c565060 24932 c579818 Clark Kent 95-10-06 c579818 15388 c576657 Lois Lane 95-10-06 c576657 9462 c572038 Bruce Wayne 95-10-06 c572038 Regular Expressions:  Regular Expressions What is a regular expression (in Perl)? a sequence or pattern of characters that is matched against a string of text when performing searches and replacements Pattern binding operators var =~/EXP/ var !~/EXP/ VAR=~s/old/new/ $name = “Tommy Tuttle”; print “Hello Tommy\n” if $name =~ /Tom/; print “$name\n” if $name !~ /Tom/; $name =~ s/T/M/; print “$name.\n”; Regular Expressions:  Regular Expressions . match any character except newline [a-z0-9] match any single char in set [^a-z] match any single char not in set \d match one digit \D same as [^0-9] \w match an alphanumeric (word) character \W match a non-alphanumeric character \s match whitespace \S match non whitespace ^ match beginning of line $ match end of line X? match 0 or 1 X X* match 0 or more X’s X+ match 1 or more X’s X{n,m} match at least n but not more than m X’s abc match a,b,c respectively was|were|will match was, were or will m and s operator:  m and s operator Searches a string for a pattern match m/pattern/i /pattern/i m is optional, i is case sensitive Substitutions s/old/new/ s/old/new/g g stands for global change on a line Examples: $cat tmp.file John Doe Jane Doe Frank Smith $perl -ne ‘s/Doe/Francois/; print; ‘ tmp.file John Francois Jane Francois Frank Smith tr and y operators:  tr and y operators Translates characters on a one-to-one correspondence, returns the number of characters replaced or deleted tr/oldlist/newlist/ y/oldlist/newlist/ (for sed users) $ARGV[1]=~y/A-Z/a-z/; #upper to lowercase $cnt = tr/*/*/; #count the stars in $_ $cnt = tr/0-9//; #count the digits tr/a-z/ / #replace lowercase chars with space Getting a filehandle:  Getting a filehandle Open for reading open(FILEHANDLE, FILENAME) open(FILEHANDLE) open FILEHANDLE Closing close (FILEHANDLE) close FILEHANDLE Do or die: function shows the open file error open(MYFILE,”file”) || die “Can’t open file:\n”; Getting a filehandle:  Getting a filehandle Open for writing or appending open(FILEHANDLE, >FILENAME) open(FILEHANDLE,>>FILENAME) Open for piping the command in the pipe will be executed open (FILEHANDLE, |PIPECMD) open (FILEHANDLE, PIPECMD |) Examples: open(INPIPE,”date |”); $today = <INPIPE>; close (INPIPE); ARGV and Null Filehandle:  ARGV and Null Filehandle When <> is used ARGV array is treated as a special filehandle Perl shifts through the array Examples % cat f1 Hello there. Nice day! % cat f2 Are you sure about this? % cat f3 Are you with me? This is kind of hard! %perl -e ‘while (<ARGV>) {print }’ f1 f2 f3 Hello there. Nice day! Are you sure about this? Are you with me? This is kind of hard! Example:  Example #!/usr/local/bin/perl $name = $ARGV[0]; open(FILE, “ypcat passwd|”); while (<FILE>) { chop; @words = split(“:”,$_); if $words[4]=~/$name/) { print “Login id “,$words[0],”\n”; print “Login Shell “,$words[6],”\n”; } } File Testing:  File Testing File testing operators -r $file true if file is readable -w $file true if file is writable … -z $file true if file is zero in size -f $file true if file is a plain file -T $file true if file is a text file -B $file true if file a binary -t $file true if file is opened to a tty Subroutines:  Subroutines Args are passed call by reference All variables created within the subroutine are global The subroutine is called by &subroutine(); do subroutine(par1,…); Define a routine sub routinename{body}; What is @_ a special array used for referencing the formal params the elements are $_[0],$_[1],… Subroutines:  Subroutines sub under { print ‘The values in the @_ array are’,”@_\n”; print “The first value is $_[0]\n”; print “The last value is “,pop(@_),”\n”; foreach $value(@_) { $value+=5; print “The value is $value\n”; } } print “Give me 5 numbers: “; @n = split(‘ ‘,<STDIN>); &under(@n); print “Back in main\n”; print “The new values are @n\n”; Give me 5 numbers: 1 2 3 4 5 The values in the @_array are 1 2 3 4 5 The first value is 1 The last value is 5 The value is 6 The value is 7 The value is 8 The value is 9 Back in main The new values are 6 7 8 9 5 WHY? Directories and Files:  Directories and Files Creating a directory mkdir(DIRNAME,MODE) %perl -e ‘mkdir(“joker”,0755)’ Other functions rmdir(DIR) chdir(EXPR) chmod(LIST) chown(LIST) opendir(DIRHANDLE, EXPR) #attach to filehandle opendir(MYDIR, “blahdir”) readdir(), telldir(),seekdir(),closedir() opendir(DIR,”..”) || die “Can’t open $!\n”; @parentfiles = readdir(DIR); closedir(DIR); foreach $file (@parentfiles) { print “$file\n”; } System function:  System function Take a UNIX command as its argument send the command to the shell for interpretation return control back to calling script system(“UNIX COMMAND”); $perl -e ‘system(“cal 10 1997”); print “Happy Halloween!”; October 1997 S M Tu W Th F S 1 2 …… Happy Halloween

#this presentations

Add a comment


petrhuertio1984o | 16/01/15
Everything was just so ? http://okibets.com/2014/12/26/gratta-e-vinci-a-brescia-vinti-500-mila-euro/

Related presentations

Related pages


Für den HTML-Code, den ein Perl-Script als CGI-Script ausgeben lassen soll, ist die Perl-Funktion print geeignet. Zum "Senden" gibt das Perl-Script ...
Read more

Perl – SELFHTML-Wiki

2 Perl/CGI Artikel aus dem Selfhtml.aktuell-Bereich Links Perl ... Beschreibung eines CGI-Scripts in Perl, das HTML-Formulare per Mail zusendet
Read more

The Perl Programming Language - www.perl.org

The Perl Programming Language at Perl.org. Links and other helpful resources for new and experienced Perl programmers.
Read more

Using Perl/CGI Scripts - Lynda.com

- Welcome to Using Perl/CGI Scripts. I'm Bill Weinman. The purpose of this course is to teach you how to use Perl/CGI Scripts. How to install them on your ...
Read more

CGI - perldoc.perl.org

This is the convention introduced long ago by Steve Brenner in his cgi-lib.pl module for Perl version 4. ... Import all methods that generate HTML 2.0 ...
Read more

CGI Programming 101: Chapter 2: Perl Variables

Chapter 2: Perl Variables. Before you can proceed much further with CGI programming, you'll need some understanding of Perl variables and data types.
Read more

Perl CGI Programming FAQ - Learn Perl - learn.perl.org

learn.perl.org. Home; Installing Perl; First steps; Modules; Examples; Documentation; Books; FAQ / Help Where will I find an answer? If you are just ...
Read more

Tutorial 2 - Using the CGI Perl Module - FEPS

The CGI.pm module. The CGI Perl module (CGI.pm) provides a simple way to create Perl CGI programs. You can use the CGI module to take care of the ...
Read more

selfhtml.de - CGI & Perl Forum - selfhtml.de - HTML lernen ...

selfhtml.de: HTML selbst erlernen und Ihre eigene Homepage erstellen - CGI & Perl Forum
Read more

Apache 2.2 CGI documentation - httpd.apache.org

The CGI (Common Gateway Interface) defines a way for a web server to interact with external content-generating programs, which are often referred to as CGI ...
Read more