Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Copyright © 2002 Pearson Education, Inc.. 2 Web Wizards Guide to CGI/Perl David Lash Chapter 3 Perl Basics.

Similar presentations


Presentation on theme: "1 Copyright © 2002 Pearson Education, Inc.. 2 Web Wizards Guide to CGI/Perl David Lash Chapter 3 Perl Basics."— Presentation transcript:

1 1 Copyright © 2002 Pearson Education, Inc.

2 2 Web Wizards Guide to CGI/Perl David Lash Chapter 3 Perl Basics

3 3 Copyright © 2002 Pearson Education, Inc. Chapter Objectives l Describe Perl scalar variables for numerical and string data l Describe Perl conditional statements l Learn how to use Perl functions l Use a function to send data to your program.

4 4 Copyright © 2002 Pearson Education, Inc. Using Scalar Variables l Variables allow you to store and access data in computer memory. l Two primary types: »Scalar variables - hold a singular item such as a number (for example, 1, 1239.12, or –123) or a character string (for example, apple, John Smith, or address). »List variables - hold a set of items (such as a set of numbers). (More in Chapter 5).

5 5 Copyright © 2002 Pearson Education, Inc. Assigning Values to Variables l Place the variables name on the left side of an equals sign (=) and the value on the right side of the equals sign. The following Perl statements use two variables: $x and $months

6 6 Copyright © 2002 Pearson Education, Inc. $X = 60; $Weeks = 4; $X = $Weeks; l Assigns 4 to $X and $Weeks. l Note: Perl variables are case sensitive. » $x and $X are considered different variable names. Assigning New Values to Variables

7 7 Copyright © 2002 Pearson Education, Inc. Selecting Variable Names l Perl variable rules »Perl variable names must have a dollar sign ( $ ) as the first character. »The second character must be a letter or underscore ( _ ). »Less than 251 characters. »Valid: $baseball, $_sum, $X, $Numb_of_bricks, $num_houses, and $counter1. » Not Valid: $123go, $1counter, and counter.

8 8 Copyright © 2002 Pearson Education, Inc. Variables and the print Place a variable name inside the double quotes of the print statement. to print out the value. E.g., »print The value of x= $x; 1. #!/usr/bin/perl 2. print Content-type: text/html\n\n; 3. $x = 3; 4. $y = 5; 5. print The value of x is $x. ; 6. print The value of y= $y.; Assign 3 to $x Assign 5 to $x

9 9 Copyright © 2002 Pearson Education, Inc. Would Output The Following:

10 10 Copyright © 2002 Pearson Education, Inc. Operating on Variables l Perl expressions are used to manipulate data values. »Use operators such as a plus sign (+) for addition and a minus sign (–) for subtraction. For example, 1. #!/usr/bin/perl 2. print Content-type: text/html\n\n; 3. $x = 3 + 4; 4. $y = 5 + $x; 5. print The value of x is $x but y = $y; Assign 7 to $x Assign 12 to $y

11 11 Copyright © 2002 Pearson Education, Inc. Would Output The following:

12 12 Copyright © 2002 Pearson Education, Inc. Some Key Perl Operators

13 13 Copyright © 2002 Pearson Education, Inc. Example Program 1. #!/usr/bin/perl 2. print Content-type: text/html\n\n; 3. $cubed = 3 ** 3; 4. $onemore = $cubed + 1; 5. $cubed = $cubed + $onemore; 6. $remain = $onemore % 3; 7. print The value of cubed is $cubed onemore= $onemore ; 8. print The value of remain= $remain; Assign 27 to $cubed Assign 55 to $cubed $remain is remainder of 28 / 3 or 1

14 14 Copyright © 2002 Pearson Education, Inc. Would Output The Following...

15 15 Copyright © 2002 Pearson Education, Inc. Writing Complex Expressions l Operator precedence rules define the order in which the operators are evaluated. l For example, consider the following expression: » $x = 5 + 2 * 6; »$x could = 56 or 17 depending on evaluation order

16 16 Copyright © 2002 Pearson Education, Inc. Perl Precedence Rules 1. Operators within parentheses. 2. Exponential operators. 3. Multiplication and division operators. 4. Addition and subtraction operators. Consider the following $X = 100 – 3 ** 2 * 2; $Y = 100 – ((3 ** 2) * 2); $Z = 100 – ( 3 ** (2 * 2) ); Evaluates to 82 Evaluates to 19

17 17 Copyright © 2002 Pearson Education, Inc. Variables with HTML Output - II 1. #!/usr/bin/perl 2. print Content-type: text/html\n\n; 3. print Example ; 4. print ; 5. $num_week = 8; 6. $total_day = $num_week * 7; 7. $num_months = $num_week / 4; 8. print Number of days are $total_day ; 9. print The total number of months=$num_months; 10. print ; Assign 28 Assign 2 Set blue font, size 5 Horizontal rule followed by black font.

18 18 Copyright © 2002 Pearson Education, Inc. Would Output The Following...

19 19 Copyright © 2002 Pearson Education, Inc. String Variables l Variables can hold numerical or character string data »For example, to hold customer names, addresses, product names, and descriptions. $letters=abc; $fruit=apple; Assign abc Assign apple Enclose in double quotes

20 20 Copyright © 2002 Pearson Education, Inc. String Variables l String variables have their own operations. »You cannot add, subtract, divide, or multiply string variables. l The concatenate operator joins two strings together and takes the form of a period (.). The repeat operator is used when you want to repeat a string a specified number of times.

21 21 Copyright © 2002 Pearson Education, Inc. Concatentate Operator Joins two strings together (Uses period (.)). $FirstName = Bull; $LastName = and Bear; $FullName1 = $FirstName. $LastName; $FullName2 = $FirstName.. $LastName; print FullName1=$FullName1 and Fullname2=$FullName2; l Would output the following: FullName1=Bulland Bear and FullName2=Bull and Bear l Note … can use double quotation marks $Fullname2 = $FirstName $LastName; »Has the same effect as $Fullname2 = $FirstName.. $LastName;

22 22 Copyright © 2002 Pearson Education, Inc. Repeat Operator l Used to repeat a string a number of times. Specified by the following sequence: $varname x 3 l For example, $score = Goal!; $lots_of_scores = $score x 3; print lots_of_scores=$lots_of_scores; l Would output the following: lots_of_scores=Goal!Goal!Goal! Repeat string value 3 times.

23 23 Copyright © 2002 Pearson Education, Inc. A Full Program Example... 1. #!/usr/bin/perl 2. print "Content-type: text/html\n\n"; 3. print " String Example "; 4. print " "; 5. $first = "John"; 6. $last = "Smith"; 7. $name = $first. $last; 8. $triple = $name x 3; 9. print " name=$name"; 10.print " triple = $triple"; 11. print " "; Concatenate Repeat

24 24 Copyright © 2002 Pearson Education, Inc. Would Output The Following...

25 25 Copyright © 2002 Pearson Education, Inc. Conditional Statements l Conditional statements enable programs to test for certain variable values and then react differently l Use conditionals in real life: »Get on Interstate 90 East at Elm Street and go east toward the city. If you encounter construction delays at mile marker 10, get off the expressway at this exit and take Roosevelt Road all the way into the city. Otherwise, stay on I-90 until you reach the city.

26 26 Copyright © 2002 Pearson Education, Inc. Conditional Statements l Perl supports 3 conditional clauses: »An if statement specifies a test condition and set of statements to execute when a test condition is true. »An elsif clause is used with an if statement and specifies an additional test condition to check when the previous test conditions are false. »An else clause is used with an if statement and possibly an elsif clause. It specifies a set of statements to execute when one or more test conditions are false.

27 27 Copyright © 2002 Pearson Education, Inc. The if Statement l Uses a test condition and set of statements to execute when the test condition is true. »A test condition uses a test expression enclosed in parentheses within an if statement. »When the test expression evaluates to true, then one or more additional statements within the required curly brackets ( { … } ) are executed.

28 28 Copyright © 2002 Pearson Education, Inc. Numerical Test Operators

29 29 Copyright © 2002 Pearson Education, Inc. Numerical Test Operators

30 30 Copyright © 2002 Pearson Education, Inc. A Sample Conditional Program 1. #!/usr/bin/perl 2. print "Content-type: text/html\n\n"; 3. print " String Example "; 4. print " "; 5. $grade = 92; 6. if ( $grade > 89 ) { 7. print Hey you got an A. ; 8. } 9. print Your actual score was $grade; 10. print ;

31 31 Copyright © 2002 Pearson Education, Inc. Would Output The Following...

32 32 Copyright © 2002 Pearson Education, Inc. Different Values of Line 5

33 33 Copyright © 2002 Pearson Education, Inc. String Test Operators l Perl supports a set of string test operators that are based on ASCII code values. »Standard, numerical representation of characters. »Every letter, number, and symbol translates into a code number. – A is ASCII code 65, and a is ASCII code 97. – Numbers are lower ASCII code values than letters, uppercase letters lower than lowercase letters. –Letters and numbers are coded in order, so that the character a is less than b, C is less than D, and 1 is less than 9.

34 34 Copyright © 2002 Pearson Education, Inc. String Test Operators

35 35 Copyright © 2002 Pearson Education, Inc. The elsif Clause l Specifies an additional test condition to check when all previous test conditions are false. »Used only with if statement »When its condition is true, gives one or more statements to execute

36 36 Copyright © 2002 Pearson Education, Inc. The elsif Clause 1. #!/usr/bin/perl 2. print Content-type: text/html\n\n; 3. $grade = 92; 4. if ( $grade > 100 ) { 5. print Illegal Grade > 100; 6. } 7. elsif ( $grade > 89 ){ 8. print Hey you got an A ; 9. } 1.0 print Your actual grade was $grade;

37 37 Copyright © 2002 Pearson Education, Inc. The elsif Clause 1. #!/usr/bin/perl 2. print Content-type: text/html\n\n; 3. $grade = 92; 4. if ( $grade >= 100 ) { 5. print Illegal Grade > 100 ; 6. } 7. elsif ( $grade < 0 ) { 8. print illegal grade < 0 ; 9. } 10. elsif ( $grade > 89 ){ 11. print Hey you got an A ; 12. } 13. print Your actual grade was $grade;

38 38 Copyright © 2002 Pearson Education, Inc. Some Sample Values for Line 3

39 39 Copyright © 2002 Pearson Education, Inc. The else Clause Specifies a set of statements to execute when all other test conditions in an if block are false. »It must be used with at least one if statement, (can also be used with an if followed by one or several elsif statements.

40 40 Copyright © 2002 Pearson Education, Inc. Using An Else Clause 1. #!/usr/bin/perl 2. print Content-type: text/html\n\n; 3. $grade = 92; 4. if ( $grade >= 100 ) { 5. print Illegal Grade > 100; 6. } 7. elsif ( $grade < 0 ) { 8. print illegal grade < 0; 9. } 10. elsif ( $grade > 89 ){ 11. print Hey you got an A; 12. } 13. else { 14. print Sorry you did not get an A; 15.}

41 41 Copyright © 2002 Pearson Education, Inc. Sample Values of Line 3 Line 3 Output $grade=92; Hey you got an A $grade=89; Sorry you did not get an A $grade=40; Sorry you did not get an A $grade=1100; Illegal Grade > 100 $grade=-50; illegal grade < 0

42 42 Copyright © 2002 Pearson Education, Inc. Using Perl Functions l Perl includes built-in functions that provide powerful additional capabilities to enhance your programs. »Work much like operators, except that most (but not all) accept one or more arguments (I.e., input values into functions).

43 43 Copyright © 2002 Pearson Education, Inc. Will Cover 3 Sets of Functions l Will discuss several functions »Some basic Perl functionsthe square root, absolute value, length, and random number generation functions. »The print functionmore details about the capabilities of the print function. »The param functionuse of this function to receive input into your programs.

44 44 Copyright © 2002 Pearson Education, Inc. S ome Basic Perl Functions l Here are a few functions within Perl »sqrt() –a single numerical argument as input & returns the square root of the argument passed in. For example, $x=25; $y=sqrt($x); print x=$x y=$y and finally, sqrt(144); would output the following: x=25 y=5 and finally 12

45 45 Copyright © 2002 Pearson Education, Inc. S ome Basic Perl Functions - abs() l Absolute Value - »abs() – accepts a single numerical argument & returns the absolute value of this argument. For example, $x=-5; $y=42; print abs($x),, abs($y); »would output the following output: 5 42 »The extra space in the print line ( ) provides a space between the output values.

46 46 Copyright © 2002 Pearson Education, Inc. S ome Basic Perl Functions -rand() l rand() – generates a random number from 0 to the number passed into it. »Example use: simulating a roll of a die or displaying a random image in a document. » When int() is used with rand(), it forces rand() to return whole numbers instead of its default fractional numbers. –For example, $numb = int( rand(3) ); –returns a random number that is either a 0, 1, or 2.

47 47 Copyright © 2002 Pearson Education, Inc. S ome Basic Perl Functions - rand() »Here is another example of the rand() function: $dice=int(rand(6))+1; print "Your random dice toss is $dice"; »The random number that is generated in this case can be a 1, 2, 3, 4, 5, or 6. Thus one possible output of this code is Your random dice toss is 6

48 48 Copyright © 2002 Pearson Education, Inc. S ome Basic Perl Functions - rand() »length() – The length function is used to work with string variables. It returns the number of characters in the string argument. For example, $name = smith; $title = Domestic Engineer; print name is, length($name), title is, length($title), characters long; »returns the following output: name is 5 title is 17 characters long

49 49 Copyright © 2002 Pearson Education, Inc. S ome Basic Perl Functions - rand() »localtime() – The localtime function is typically used with the time() function to determine the current date and time while your program is executing. – time returns the number of seconds since January 1, 1970. –When time() is used as an argument to the localtime() function, the output will be a set of scalar variables that provide the current date and time information. –For example,

50 50 Copyright © 2002 Pearson Education, Inc. locatltime(time) return values ($sec, $min, $hr, $day, $mon, $yr, $wkday, $DayNumOfYr, $TZ ) = localtime(time); Current second Current minute Current Hour Day Of Month (0 is Jan, 1 is Feb, etc) Number of years since 1900. Day of week (0 is Sun, 1 is Mon, since 1900. Day of year (0 is Jan1, 1 is Jan 2, etc.) Timezone 1 if local time is using Daylight Savings Time; 0 otherwise

51 51 Copyright © 2002 Pearson Education, Inc. Using localtime(time) ($sec, $min, $hr, $day, $mon, $yr, $wkday, $DayNumOfYr, $TZ ) = localtime(time); print "Time is $hr:$min:$sec Date=$mon/$day/$yr ";\ print "Wkday=$wkday DayNumbOfYear=$DayNumOfYr $TZ=$TZ; Would produce the following example output: »Time is 21:12:58 Date=7/15/101 Wkday=3 DayNumbOfYear=226 1=1

52 52 Copyright © 2002 Pearson Education, Inc. More Common Localtime Use »The following code shows a common use of localtime() to get date information: ($sec, $min, $hr, $day, $mon, $yr, $wkday, $DayNumOfYr, $TZ ) = localtime(time); $yr=$yr+1900; $mon = $mon + 1; print "Time is $hr:$min:$sec Date=$mon/$day/$yr "; print "Wkday=$wkday DayNumbOfYear=$DayNumOfYr $TZ=$TZ"; The output would look like the following: Time is 21:29:58 Date=8/15/2001 Wkday=3 DayNumbOfYear=226 1=1

53 53 Copyright © 2002 Pearson Education, Inc. The print Function l You can enclose output in parentheses or not. l When use double quotation marks, Perl outputs the value of any variables. For example, $x = 10; print ("Mom, please send $x dollars"); l Output the following message: Mom, please send 10 dollars

54 54 Copyright © 2002 Pearson Education, Inc. More On print() l If want to output the actual variable name (and not its value), then use single quotation marks. $x = 10; print ( 'Mom, please send $x dollars'); l Would output the following message: Mom, please send $x dollars

55 55 Copyright © 2002 Pearson Education, Inc. Still More On print() l Can also comma separate several arguments to print(). For example, $x=5; print ('Send $bucks', " need $x. No make that ", 5*$x); This print statement request would output the following message: Send $bucks need 5. No make that 25

56 56 Copyright © 2002 Pearson Education, Inc. Generating HTML with print() l Can use single quotes when output some HTML tags: print ; Can use backslash ( \ ) to signal that double quotation marks themselves should be output: $color=BLUE; print ;

57 57 Copyright © 2002 Pearson Education, Inc. The param Function l Most programs receive some sort of input. »The param() function enables a CGI/Perl program to receive input. »It is available within the CGI.pm library. – A Perl library comprises a collection of functions available to your program once the program connects to it. –The CGI.pm functions were created by Lincoln Stein and have been incorporated into the standard Perl library since Perl version 5.003

58 58 Copyright © 2002 Pearson Education, Inc. Connecting to param() l Before you can use param() must connect to CGI.pm library:

59 59 Copyright © 2002 Pearson Education, Inc. Using param l Input variables into CGI/Perl application programs are called CGI variables. »Values received through your Web server as input from a Web browser. l To use param() (after connecting to it):

60 60 Copyright © 2002 Pearson Education, Inc. Getting The Input Values... 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print "Content-type: text/html\n\n"; 4. $grade = param('mygrade'); 5. print ("Got a Grade = $grade");

61 61 Copyright © 2002 Pearson Education, Inc. Sending Arguments l It is useful to send arguments to your program directly from the URL address of a browser.

62 62 Copyright © 2002 Pearson Education, Inc. Sending Multiple Arguments Precede first argument with ? Precede next argument with &

63 63 Copyright © 2002 Pearson Education, Inc. Example Full Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print "Content-type: text/html\n\n"; 4. print ' Grade '; 5. $grade = param('mygrd'); 6. $name = param('myname'); 7. print ' '; 8. if ( $grade >= 100 ) { 9. print 'Illegal Grade > 100'; 10. } elsif ( $grade < 0 ) { 11. print 'illegal grade < 0'; 12. } elsif ( $grade >= 90 ){ 13. print 'Hey you got an A'; 14. } else { 15. print 'Sorry you did not get an A'; 16. } 17. print ' '; 18. print "$name, your grade was $grade"; 19. print ;

64 64 Copyright © 2002 Pearson Education, Inc. Would Output The Following...

65 65 Copyright © 2002 Pearson Education, Inc. Testing For Null Value l Perl provides a simple method to test if any parameters were received: $name = param( uname ) ; if ($name) { statement(s) to execute when $name has a value } else { statement(s) to execute when $name has no value }

66 66 Copyright © 2002 Pearson Education, Inc. Summary l Variables are used to store and access data in computer memory. l Numerical and string variables have unique operations that can be used to manipulate their values. l Conditional statements are used to test for conditions and, based on the results of the test, execute specific program statements. Perl provides different test condition operators for string and numerical variables.

67 67 Copyright © 2002 Pearson Education, Inc. Summary The if statement can be used by itself and is a basic way of testing conditions. The elsif clause can be used with the if statement to provide another test condition when the original if statement is false. An else clause provides statements that execute when all other if and elsif conditions are false.

68 68 Copyright © 2002 Pearson Education, Inc. Summary There are many built-in Perl functions that are useful. These functions, which include print(), sqrt(), and length(), can be used directly in programs when needed. The param() function is found in the CGI.pm library. Must connect to this library before you can use it. »It is useful for receiving arguments into your program. Arguments can be sent to your program from the address or location box of a Web browser connected to the Internet.


Download ppt "1 Copyright © 2002 Pearson Education, Inc.. 2 Web Wizards Guide to CGI/Perl David Lash Chapter 3 Perl Basics."

Similar presentations


Ads by Google