Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental Variables and Functions.

Similar presentations


Presentation on theme: "1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental Variables and Functions."— Presentation transcript:

1 1 Copyright © 2002 Pearson Education, Inc.

2 2 Chapter 6 Hashes (Associative Arrays), Environmental Variables and Functions

3 3 Copyright © 2002 Pearson Education, Inc. Chapter Objectives l Describe how to use hash lists and hash tables in Perl l Look at Perl Environmental Variables l Learn how to use subroutines in a programs l Combine form generation and processing into a single program

4 4 Copyright © 2002 Pearson Education, Inc. Chapter Objectives l Describe how to use hash lists and hash tables in Perl l Look at Perl Environmental Variables l Learn how to use subroutines in a programs l Combine form generation and processing into a single program

5 5 Copyright © 2002 Pearson Education, Inc. Hash Lists (or associated arrays) l A type of array that uses string indices instead of sequential numbers. l Items not stored sequentially but stored in pairs of values »the first item the key, the second the data »The key is used to look up or provide a cross-reference to the data value. »Instead of using sequential subscripts to refer to data in a list, you use keys.

6 6 Copyright © 2002 Pearson Education, Inc. Advantages of Hash Lists l Need to cross-reference one piece of data with another. »Perl supports some convenient functions that use hash lists for this purpose. (E.g,. You cross reference a part number with a product description.) l Concerned about the access time required for looking up data. »Hash lists provide quicker access to cross- referenced data. E.g, have a large list of product numbers and product description, cost, and size, pictures).

7 7 Copyright © 2002 Pearson Education, Inc. Using Hash Lists l General Format to define a hash list: l Alternate syntax %months = ( "Jan" => 31, "Feb" => 28, "Mar" => 31, "Apr" => 30, "May" => 31, "Jun" => 30, "Jul" => 31, "Aug" => 31, "Sep" => 30, "Oct" => 31,"Nov" => 30, "Dec" => 31 );

8 8 Copyright © 2002 Pearson Education, Inc. Accessing Items From A Hash List

9 9 Copyright © 2002 Pearson Education, Inc. Accessing Items From a Hash List l When access an individual item, use the following syntax: Note: You Cannot Fetch Keys by Data Values. This is NOT valid : $mon = $months{ 28 };

10 10 Copyright © 2002 Pearson Education, Inc. Complete Example... l Consider a Web Application that »Allows you select a start month and day »Outputs number of days left in month »Calling form: » Jan Feb Mar..

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

12 12 Copyright © 2002 Pearson Education, Inc. Example Hash List Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html( 'Month Calc' ); 4. %months = ( "Jan", 31, "Feb", 28, "Mar", 31, "Apr", 30, "May", 31, "Jun", 30, "Jul", 31, "Aug", 31, "Sep", 30,"Oct", 31, "Nov", 30, "Dec", 31 ); 5. $startm = param('startmon'); 6. $startd = param('startday'); 7. $mdays=$months{ "$startm" }; 8. if ( $startd <= $mdays ) { 9. $daysLeft = $mdays - $startd; 10. print "There are $daysLeft days left in $startm."; 11. print br, "$startm has $mdays total days "; 12. } else { 13. print "Hmmm, there aren't $startd day in $startm"; 14. } 15. print end_html;

13 13 Copyright © 2002 Pearson Education, Inc. Hash Keys and Values Access Functions The keys() function returns a list of all keys in the hash list. For example, %Inventory = ( 'Nuts', 33, 'Bolts', 55, 'Screws', 12); @keyitems = keys(%Inventory); print “keyitems= @keyitems”; l Perl outputs hash keys and values according to how they are stored internally. So, 1 possible output order: keyitems= Screws Bolts Nuts

14 14 Copyright © 2002 Pearson Education, Inc. Keys() & values() are often used to output the contents of a hash list. For example, % Inventory = ( 'Nuts', 33, 'Bolts', 55, 'Screws', 12); foreach $item ( (keys %Inventory) ) { print "Item=$item Value=$Inventory{$item} "; } l The following is one possible output order: Item=Screws Value=12 Item=Bolts Value=55 Item=Nuts Value=33 Using keys() and values()

15 15 Copyright © 2002 Pearson Education, Inc. Changing a Hash Element l You can change the value of a hash list item by giving it a new value in an assignment statement. For example, %Inventory = ( 'Nuts', 33, 'Bolts', 55, 'Screws', 12); $Inventory{‘Nuts’} = 34; This line changes the value of the value associated with Nuts to 34.

16 16 Copyright © 2002 Pearson Education, Inc. Adding a Hash Element l You can add items to the hash list by assigning a new key a value. For example, %Inventory = ( 'Nuts', 33, 'Bolts', 55, 'Screws', 12); $Inventory{‘Nails’} = 23; These lines add the key Nails with a value of 23 to the hash list.

17 17 Copyright © 2002 Pearson Education, Inc. Deleting a Hash Element You can delete an item from the hash list by using the delete() function. For example, %Inventory = ( 'Nuts', 33, 'Bolts', 55, 'Screws', 12); delete $Inventory{‘Bolts’}; These lines delete the Bolts key and its value of 55 from the hash list.

18 18 Copyright © 2002 Pearson Education, Inc. Quick Case Study l Consider the program at l http://hawk.depaul.edu/cgi- bin/cgiwrap/dlash/drive_distance.cgi http://hawk.depaul.edu/cgi- bin/cgiwrap/dlash/drive_distance.cgi l It is a front-end form to calc distances. l It calls the program at l http://hawk.depaul.edu/cgi- bin/cgiwrap/dlash/distance.cgi http://hawk.depaul.edu/cgi- bin/cgiwrap/dlash/distance.cgi

19 19 Copyright © 2002 Pearson Education, Inc. Verifying an Element’s Existence Use the exists() function verifies if a particular key exists in the hash list. » It returns true ( 1) if the key exists. (False if not). For example: %Inventory = ( 'Nuts', 33, 'Bolts', 55, 'Screws', 12); if ( exists( $Inventory{‘Nuts’} ) ) { print ( “Nuts are in the list” ); } else { print ( “No Nuts in this list” ); } l This code outputs Nuts are in the list.

20 20 Copyright © 2002 Pearson Education, Inc. Quick Case Study l Consider the program at l http://hawk.depaul.edu/cgi- bin/cgiwrap/dlash/drive_distance.cgi http://hawk.depaul.edu/cgi- bin/cgiwrap/dlash/drive_distance.cgi l It is a front-end form to calc distances. l It calls the program at l http://hawk.depaul.edu/cgi- bin/cgiwrap/dlash/distance.cgi http://hawk.depaul.edu/cgi- bin/cgiwrap/dlash/distance.cgi

21 21 Copyright © 2002 Pearson Education, Inc. Complete Example... l Consider a Web Application that »Allows you add an item to a hash list. »Allows “add” or “Delete” option but only implement “add” »Calling form: » Operation? Add Unknown

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

23 23 Copyright © 2002 Pearson Education, Inc. Example Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html( 'Inventory' ); 4. %invent = ( "Nuts", 44, "Nails", 34, "Bolts", 31 ); 5. $action = param('Action'); 6. $whatkey = param('Key'); 7. $whatvalue = param('Value'); 8. if ( $action eq "Add" ) { 9. if ( exists( $invent{ "$whatkey" } ) ) { 10. print "Sorry already exists $whatkey "; 11. } else { 12. $invent{"$whatkey"} = $whatvalue; 13. print "Adding key=$whatkey val=$whatvalue "; 14. print "----- "; 15. foreach $key ( ( keys %invent ) ) { 16. print "$invent{$key} key=$key "; 17. } 18. } 19. } else { print "Sorry No Such Action=$action "; } 20. print end_html;

24 24 Copyright © 2002 Pearson Education, Inc. Chapter Objectives l Describe how to use hash lists and hash tables in Perl l Look at Perl Environmental Variables l Learn how to use subroutines in a programs l Combine form generation and processing into a single program

25 25 Copyright © 2002 Pearson Education, Inc. Environmental Hash Lists l When your Perl program starts from a Web browser, a special environmental hash list is made available to it. »Comprises a hash list that describe the environment (state) when your program was called. (called the %ENV hash). l Can be used just like any other hash lists. For example,

26 26 Copyright © 2002 Pearson Education, Inc. Some environmental variables HTTP_REFFERER - defines the URL of the Web page that the user accessed prior to accessing your page. »For example, a value of HTTP_REFFERER might be “http://www.mypage.com”. »Set when someone links to or reaches your site via the submit button. »Useful to check if your program was called from the your form-generating program. (Might reject anyone accessing from somewhere else)

27 27 Copyright © 2002 Pearson Education, Inc. Some environmental variables REQUEST_USER_AGENT. defines the browser name, browser version, and computer platform of the user who is starting your program. » For example, its value might be “Mozilla/4.7 [en] (Win 98, I)” for Netscape. » You may find this value useful if you need to output browser-specific HTML code.

28 28 Copyright © 2002 Pearson Education, Inc. Some environmental variables HTTP_ACCEPT_LANGUAGE - defines the language that the browser is using. »E.g., might be “en” for English for Netscape or “en-us” for English for Internet Explorer. REMOTE_ADDRESS - indicates the TCP/IP address of the computer that is accessing your site. »(ie., the physical network addresses of computers on the Internet —for example, 65.186.8.8.) »May have value if log visitor information

29 29 Copyright © 2002 Pearson Education, Inc. Some environmental variables REMOTE_HOST - set to the domain name of the computer connecting to your Web site. »It is a logical name that maps to a TCP/IP address—for example, www.yahoo.com. »It is empty if the Web server cannot translate the TCP/IP address into a domain name. l There are many other environmental variables.

30 30 Copyright © 2002 Pearson Education, Inc. Complete example … l Consider a CGI/Perl program that checks the language. »Output one message when english »Another when not. l Need to check how both IE and Netscape set »$ENV{'HTTP_ACCEPT_LANGUAGE' »'en' or 'en-us'

31 31 Copyright © 2002 Pearson Education, Inc. Example: Checking Language 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html('Check Environment'); 4. $lang=$ENV{'HTTP_ACCEPT_LANGUAGE'}; 5. if ( $lang eq 'en' || $lang eq 'en-us' ) { 6. print "Language=$ENV{'HTTP_ACCEPT_LANGUAGE'}"; 7. print " Browser= $ENV{'HTTP_USER_AGENT'}"; 8. } 9. else { 10. print 'Sorry I do not speak your language'; 11. } 12. print end_html;

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

33 33 Copyright © 2002 Pearson Education, Inc. Checking Browser Types $browser=$ENV{'HTTP_USER_AGENT'} ; if ( $browser =~ m/MSIE/ ) { print "Got Internet Explorer Browser=$browser"; } else { print "browser=$browser"; }

34 34 Copyright © 2002 Pearson Education, Inc. Chapter Objectives l Describe how to use hash lists and hash tables in Perl l Look at Perl Environmental Variables l Learn how to use subroutines in a programs l Combine form generation and processing into a single program

35 35 Copyright © 2002 Pearson Education, Inc. Chapter Objectives l Describe how to use hash lists and hash tables in Perl l Look at Perl Environmental Variables l Learn how to use subroutines in a programs l Combine form generation and processing into a single program

36 36 Copyright © 2002 Pearson Education, Inc. Using Subroutines l Subroutines provide a way for programmers to group a set of statements, set them aside, and turn them into mini-programs within a larger program. l These mini-programs can be executed several times from different places in the overall program

37 37 Copyright © 2002 Pearson Education, Inc. Subroutine Advantages l Smaller overall program size. Can place statements executed several times into a subroutine and just call them when needed. l Programs that are easier to understand and change. Subroutines can make complex and long programs easier to understand and change. (e.g., Divide into logical sections). l Reusable program sections. You might find that some subroutines are useful to other programs. (E.g, Common page footer). common page footer.

38 38 Copyright © 2002 Pearson Education, Inc. Working with Subroutines l You can create a subroutine by placing a group of statements into the following format: sub subroutine_name { set of statements } For example a outputTableRow subroutine sub outputTableRow { print ‘ One Two ’; } Execute the statements in this subroutine, by preceding the name by an ampersand: &outputTableRow;

39 39 Copyright © 2002 Pearson Education, Inc. Subroutine Example Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html( 'Subroutine Example' ); 4. print 'Here is simple table '; 5. &outputTableRow; 6. &outputTableRow; 7. &outputTableRow; 8. print ' ', end_html; 9. sub outputTableRow { 10. print ' One Two '; 11. } Call subroutine Three times. Subroutine definition

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

41 41 Copyright © 2002 Pearson Education, Inc. Passing Arguments to Subroutines l Generalize a subroutine using input variables (called arguments to the subroutine). &outputTableRow( ‘A First Cell’, ‘A Second Cell’ ); l Use @_ (underbar array) to access arguments: $_[0] as the variable name for the first argument, $_[1] as the variable name for the second argument, $_[2] as the variable name for the third argument,. $_[n] as the variable name for the n th argument. Array name

42 42 Copyright © 2002 Pearson Education, Inc. Passing Arguments to Subroutines Suppose outputTableRow subroutine was called as shown below: &outputTableRow( ‘A First Cell’, ‘A Second Cell’ ); Then »$_[0] would be set to ‘A First Cell’ and »$_[1] would be set to ‘A Second Cell’ : First argument Second argument

43 43 Copyright © 2002 Pearson Education, Inc. Full Subroutine Example 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html( 'Subroutine with arguments' ); 4. print 'Here is simple table: '; 5. for ( $i=1; $i<=3; $i++ ) { 6. &outputTableRow( "Row $i Col 1", "Row $i Col 2"); 7. } 8. print ' ', end_html; 9. sub outputTableRow { 10. print " $_[0] $_[1] "; 11. } First Argument Second Argument arguments

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

45 45 Copyright © 2002 Pearson Education, Inc. Getting the Number of Arguments l There are at least two different ways … »The range operator is set to the last element in a list variable. Therefore, within a subroutine the number of arguments is: –$numargs = $#_ + 1; »Second, you can use the @_ variable directly. For example, – $numargs = @_; More Commonly used

46 46 Copyright © 2002 Pearson Education, Inc. Returning Values l Subroutines can return values to the calling program. (Auseful way to send the results of a computation) »$result = sqrt(144); l To Return a value within a subroutine: l Stops the subroutine execution and return the specified value to the calling program. Returns 12 to $result

47 47 Copyright © 2002 Pearson Education, Inc. Example Subroutine Return Value $largest = &simple_calc( $num1, $num2 ); 1. sub simple_calc { 2. # PURPOSE: returns largest of 2 numbers 3. # ARGUMENTS $[0] – 1 st number, $_[1] – 2 nd number 4. if ( $[0] > $[1] ) { 5. return( $[0] ); 6. } else { 7. return( $[1] ); 8. } 9. } Return arg1 if bigger Return arg2 If bigger

48 48 Copyright © 2002 Pearson Education, Inc. Abbreviated way to check for 0 returned l Can check for 0 returned very concisely if ( myfunction(4) ) { stuff to do if not 0 } else { stuff to do if 0 } Or Alternatively if ( !myfunction(4) ) { stuff to do if 0 } else { stuff to do if not 0 } Perhaps Output an error

49 49 Copyright © 2002 Pearson Education, Inc. For example,... Ask for Input. Not allow words like “mud”

50 50 Copyright © 2002 Pearson Education, Inc. Example Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html('Input Check '); 4. @dirty=('mud', 'dirt', 'slime', 'grease'); 5. $input=param('uinput'); 6. if ( &CheckInput($input ) ) { 7. print "Input received: $input"; 8. } else { 9. print "Sorry I cannot accept the input=$input"; 10. } 11. sub CheckInput { 12. foreach $item ( @dirty ) { 13. if ( $_[0] =~ m/$item/ ) { 14. print "Hey $item is not clean!", br; 15. return 0; 16. } 17. } 18. return 1; 19. } Matches if $item is found Return 0 if Found it. If 0 returned OK Else not OK

51 51 Copyright © 2002 Pearson Education, Inc. Chapter Objectives l Describe how to use hash lists and hash tables in Perl l Look at Perl Environmental Variables l Learn how to use subroutines in a programs l Combine form generation and processing into a single program

52 52 Copyright © 2002 Pearson Education, Inc. Combining Program Files l Applications so far have required two separate files; one file for to generate the form, and the other to parse the form. »Can test return value on param() to combine these. l At least two advantages »With one file, it is easier to change arguments »It is easier to maintain one file.

53 53 Copyright © 2002 Pearson Education, Inc. Combining Program Files Note: Often times will use this to work on one form and “stub” the other. Would build them incrementally.

54 54 Copyright © 2002 Pearson Education, Inc. Consider the following “app”...

55 55 Copyright © 2002 Pearson Education, Inc. Example Combination Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header; 4. if ( !param() ) { create_form(); } 5. else { process_form(); } 6. sub create_form() { 7. # PURPOSE: Use this to create form 8. print start_html( 'Create Form' ); 9. print ' '; 10. print " How we doing? "; 11. print ' '; 12. print br, ' '; 13. print ' '; 14. print ' ', end_html; 15. } 16. sub process_form() { 17. # Use this to process the form 18. print start_html( 'Received Form '); 19. $answ=param('doing'); 20. print " You Said... "; 21. print "$answ", end_html; 22. } Creates initial form. Receive values and generate next screen.

56 56 Copyright © 2002 Pearson Education, Inc. l It is sometimes useful to place sub-routines in external separate files to promote their reuse »Other programs can use them without creating separate copies l To store in external file: 1.Move subroutine lines to a new file. For example, move outputTableRow sub outputTableRow { print ' One Two '; } Using Subroutines in External Files

57 57 Copyright © 2002 Pearson Education, Inc. 2.Place a 1 at the end of the new file. This step provides a return value of 1, which helps Perl recognize that the subroutine executed successfully. 3.Name the subroutine file. Usually, this file has a.lib suffix, which indicates that it is a library file of subroutines. For example, you might call the file startdoc.lib. Using Subroutines in External Files

58 58 Copyright © 2002 Pearson Education, Inc. 4.Place the file in the same directory as the program file. (Can reside in another directory but For now assume in same.) 5.Include an additional require line in the calling program. Before a program can use the subroutine library file, it must add a line that indicates where to look for that file. This line has the following format: »require ‘library_filename’; Using Subroutines in External Files

59 59 Copyright © 2002 Pearson Education, Inc. Example External Subroutine File 1. sub outputTableRow { 2. # PURPOSE: outputs a table row with 2 cols 3. # ARGUMENTS: uses $_[0] for first col 4. # : uses $_[1] for second col 5. print " $_[0] $_[1] "; 6. } 7. sub specialLine { 8. # PURPOSE: Output a line with varible color: 9. # ARGUMENTS: $_[0] is the line to output 10. # : $_[1] is the line color. 11. print " $_[0] "; 12. } 13. 1

60 60 Copyright © 2002 Pearson Education, Inc. Example Calling Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. require 'htmlhelper1.lib'; 4. print header, start_html('Some External Subroutines'); 5. &specialLine( 'Here is a simple table', 'RED' ); 6. print ' '; 7. print ' Num Num Cubed '; 8. for ( $i=0; $i<3; $i++ ) { 9. &outputTableRow( $i, $i**3 ); 10. } 11. print ' ', end_html; Call external routine

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

62 62 Copyright © 2002 Pearson Education, Inc. Summary l Hash lists store data in name/value pairs instead of sequentially ordered list variables. »They can be very useful for cross-referencing data, and they allow for much faster data lookups than do list variables. l Perl uses special operations for adding and deleting hash list items, checking whether hash keys exist, and getting lists of keys and values.

63 63 Copyright © 2002 Pearson Education, Inc. Summary - II l Hash tables are lists indexed by keys. Using a common key, you can find the entire list of information. The environmental hash list, which is called %ENV, contains environmental variables that describe how your program was called.

64 64 Copyright © 2002 Pearson Education, Inc. Summary - III l Subroutines set aside a group of statements and them into mini-programs within a larger program. »These mini-programs can be executed several times from different program. l Subroutines can be called anywhere from within a program as often as necessary. » Can pass them arguments that provide input data to the subroutines. » Subroutines can also return values and be placed in external files so that they can be shared.


Download ppt "1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental Variables and Functions."

Similar presentations


Ads by Google