1 / 64

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

Chapter 6 Hashes (Associative Arrays), Environmental Variables and Functions. Chapter Objectives. Describe how to use hash lists and hash tables in Perl Look at Perl Environmental Variables Learn how to use subroutines in a programs

gyan
Download Presentation

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

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Chapter Objectives • Describe how to use hash lists and hash tables in Perl • Look at Perl Environmental Variables • Learn how to use subroutines in a programs • Combine form generation and processing into a single program

  3. Chapter Objectives • Describe how to use hash lists and hash tables in Perl • Look at Perl Environmental Variables • Learn how to use subroutines in a programs • Combine form generation and processing into a single program

  4. Hash Lists (or associated arrays) • A type of array that uses string indices instead of sequential numbers. • 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.

  5. Advantages of Hash Lists • 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.) • 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).

  6. Using Hash Lists • General Format to define a hash list: • 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 );

  7. Accessing Items From A Hash List

  8. Accessing Items From a Hash List • When access an individual item, use the following syntax: • Note: You Cannot Fetch Keys by Data Values. This is NOT valid: $mon = $months{ 28 };

  9. Complete Example. . . • Consider a Web Application that • Allows you select a start month and day • Outputs number of days left in month • Calling form: • <FORM ACTION=“http://65.108.8.8/cgi-bin/C6/drivehash1.cgi”> <BR> <SELECT NAME=“startmon" SIZE=3 > <OPTION selected>Jan <OPTION>Feb <OPTION>Mar . . . </SELECT> . . .

  10. Would Output The Following ...

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

  12. 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”; • Perl outputs hash keys and values according to how they are stored internally. So, 1 possible output order: keyitems= Screws Bolts Nuts

  13. Using keys() and values() 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} "; } • The following is one possible output order: Item=Screws Value=12 Item=Bolts Value=55 Item=Nuts Value=33

  14. Changing a Hash Element • 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.

  15. Adding a Hash Element • 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.

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

  17. Quick Case Study • Consider the program at • http://hawk.depaul.edu/cgi-bin/cgiwrap/dlash/drive_distance.cgi • It is a front-end form to calc distances. • It calls the program at • http://hawk.depaul.edu/cgi-bin/cgiwrap/dlash/distance.cgi

  18. 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” ); } • This code outputs Nuts are in the list.

  19. Quick Case Study • Consider the program at • http://hawk.depaul.edu/cgi-bin/cgiwrap/dlash/drive_distance.cgi • It is a front-end form to calc distances. • It calls the program at • http://hawk.depaul.edu/cgi-bin/cgiwrap/dlash/distance.cgi

  20. Complete Example. . . • 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: • <FORM ACTION=“http://65.108.8.8/cgi-bin/C6/hashadd.cgi”> <BR> Operation? <INPUT RADIO NAME=“Action” Value=“Add” > Add <INPUT RADIO NAME=“Action” Value=“Unkonwn” > Unknown <BR> <INPUT TEXT NAME=“Key” > <INPUT TEXT NAME=“Value” > </FORM>

  21. Would Output The Following ..

  22. 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 <BR>"; 11. } else { 12. $invent{"$whatkey"} = $whatvalue; 13. print "Adding key=$whatkey val=$whatvalue <BR>"; 14. print "-----<BR>"; 15. foreach $key ( ( keys %invent ) ) { 16. print "$invent{$key} key=$key <BR>"; 17. } 18. } 19. } else { print "Sorry No Such Action=$action<BR>"; } 20. print end_html;

  23. Chapter Objectives • Describe how to use hash lists and hash tables in Perl • Look at Perl Environmental Variables • Learn how to use subroutines in a programs • Combine form generation and processing into a single program

  24. Environmental Hash Lists • When your Perl program starts from a Web browser, a special environmental hash listis made available to it. • Comprises a hash list that describe the environment (state) when your program was called. (called the %ENVhash). • Can be used just like any other hash lists. For example,

  25. 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)

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

  27. 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 thatis 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

  28. 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. • There are many other environmental variables.

  29. Complete example … • Consider a CGI/Perl program that checks the language. • Output one message when english • Another when not. • Need to check how both IE and Netscape set • $ENV{'HTTP_ACCEPT_LANGUAGE' • 'en' or 'en-us'

  30. 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 "<BR>Browser= $ENV{'HTTP_USER_AGENT'}"; 8. } 9. else { 10. print 'Sorry I do not speak your language'; 11. } 12. print end_html;

  31. Would Output The Following ...

  32. Checking Browser Types $browser=$ENV{'HTTP_USER_AGENT'} ; if ( $browser =~ m/MSIE/ ) { print "Got Internet Explorer Browser=$browser"; } else { print "browser=$browser"; }

  33. Chapter Objectives • Describe how to use hash lists and hash tables in Perl • Look at Perl Environmental Variables • Learn how to use subroutines in a programs • Combine form generation and processing into a single program

  34. Chapter Objectives • Describe how to use hash lists and hash tables in Perl • Look at Perl Environmental Variables • Learn how to use subroutines in a programs • Combine form generation and processing into a single program

  35. Using Subroutines • 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. • These mini-programs can be executed several times from different places in the overall program

  36. Subroutine Advantages • Smaller overall program size. Can place statements executed several times into a subroutine and just call them when needed. • 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). • Reusable program sections. You might find that some subroutines are useful to other programs. (E.g, Common page footer). common page footer.

  37. Working with Subroutines • 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 ‘<TR><TD>One</TD><TD>Two</TD></TR>’; } • Execute the statements in this subroutine, by preceding the name by an ampersand: &outputTableRow;

  38. Subroutine Example Program 1. #!/usr/bin/perl 2. use CGI ':standard'; 3. print header, start_html( 'Subroutine Example' ); 4. print 'Here is simple table <TABLE BORDER=1>'; 5. &outputTableRow; 6. &outputTableRow; 7. &outputTableRow; 8. print '</TABLE>', end_html; 9. sub outputTableRow { 10. print '<TR><TD>One</TD><TD>Two</TD></TR>'; 11.} Call subroutine Three times. Subroutine definition

  39. Would Output The Following …

  40. PassingArguments to Subroutines • Generalize a subroutine using input variables (called arguments to the subroutine). &outputTableRow( ‘A First Cell’, ‘A Second Cell’ ); • 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 nth argument. Array name

  41. PassingArguments 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

  42. 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: <TABLE BORDER=1>'; 5.for ( $i=1; $i<=3; $i++ ) { 6. &outputTableRow( "Row $i Col 1", "Row $i Col 2"); 7. } 8. print '</TABLE>', end_html; 9. sub outputTableRow { 10. print "<TR><TD>$_[0]</TD><TD>$_[1]</TD></TR>"; 11. } arguments First Argument Second Argument

  43. Would Output The Following ...

  44. Getting the Number of Arguments • 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

  45. Returning Values • Subroutines can return values to the calling program. (Auseful way to send the results of a computation) • $result = sqrt(144); • To Return a value within a subroutine: • Stops the subroutine execution and return the specified value to the calling program. Returns 12 to $result

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

  47. Abbreviated way to check for 0 returned • 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

  48. For example, ... Ask for Input. Not allow words like “mud”

  49. 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. } If 0 returned OK Else not OK Matches if $item is found Return 0 if Found it.

More Related