64
1 Copyright © 2002 Pearson Education, Inc.

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

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

1 Copyright © 2002 Pearson Education, Inc.

Page 2: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

2 Copyright © 2002 Pearson Education, Inc.

Chapter 6Hashes (Associative Arrays), Environmental

Variables and Functions

Page 3: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

3 Copyright © 2002 Pearson Education, Inc.

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

Page 4: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

4 Copyright © 2002 Pearson Education, Inc.

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

Page 5: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

5 Copyright © 2002 Pearson Education, Inc.

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.

Page 6: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

6 Copyright © 2002 Pearson Education, Inc.

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

Page 7: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

7 Copyright © 2002 Pearson Education, Inc.

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

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

Name of hash list variable start with '%'.Key element 1 and data element 1.

Key element 2 and data element 2.Key element 3 and data element 3.

Page 8: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

8 Copyright © 2002 Pearson Education, Inc.

Accessing Items From A Hash List

$day = $months{'Mar'};

Requests touse this key tofetch it's value.

Starts with'$' since,resultsis scalar.

Enclose incurly brackets.

Page 9: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

9 Copyright © 2002 Pearson Education, Inc.

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

$day = $months{'Mar'};

Requests touse this key tofetch it's value.

Starts with'$' since,resultsis scalar.

Enclose incurly brackets.

Page 10: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

10 Copyright © 2002 Pearson Education, Inc.

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

Page 11: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

11 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

Page 12: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

12 Copyright © 2002 Pearson Education, Inc.

Example Hash List Program

1. #!/usr/bin/perl2. 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;

Page 13: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

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

Perl outputs hash keys and values according to how they are stored internally. So, 1 possible output order:

keyitems= Screws Bolts Nuts

Page 14: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

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} ";}

The following is one possible output order: Item=Screws Value=12 Item=Bolts Value=55 Item=Nuts Value=33

Using keys() and values()

Page 15: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

15 Copyright © 2002 Pearson Education, Inc.

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.

Page 16: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

16 Copyright © 2002 Pearson Education, Inc.

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.

Page 17: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

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.

Page 18: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

18 Copyright © 2002 Pearson Education, Inc.

Quick Case Study

Consider the program at http://hawk.depaul.edu/cgi-bin/cgiwrap/dlash/dri

ve_distance.cgi It is a front-end form to calc distances. It calls the program at http://hawk.depaul.edu/cgi-bin/cgiwrap/dlash/di

stance.cgi

Page 19: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

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

} This code outputs

Nuts are in the list.

Page 20: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

20 Copyright © 2002 Pearson Education, Inc.

Quick Case Study

Consider the program at http://hawk.depaul.edu/cgi-bin/cgiwrap/dlash/dri

ve_distance.cgi It is a front-end form to calc distances. It calls the program at http://hawk.depaul.edu/cgi-bin/cgiwrap/dlash/di

stance.cgi

Page 21: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

21 Copyright © 2002 Pearson Education, Inc.

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>

Page 22: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

22 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ..

Page 23: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

23 Copyright © 2002 Pearson Education, Inc.

Example Program1. #!/usr/bin/perl2. 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;

Page 24: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

24 Copyright © 2002 Pearson Education, Inc.

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

Page 25: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

25 Copyright © 2002 Pearson Education, Inc.

Environmental Hash Lists 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).

Can be used just like any other hash lists. For example, print “Language=$ENV{‘HTTP_ACCEPT_LANGUAGE’}”;

Page 26: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

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)

Page 27: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

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.

Page 28: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

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

Page 29: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

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

Page 30: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

30 Copyright © 2002 Pearson Education, Inc.

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'

Page 31: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

31 Copyright © 2002 Pearson Education, Inc.

Example: Checking Language1. #!/usr/bin/perl2. 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;

Page 32: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

32 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

Page 33: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

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";}

Page 34: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

34 Copyright © 2002 Pearson Education, Inc.

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

Page 35: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

35 Copyright © 2002 Pearson Education, Inc.

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

Page 36: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

36 Copyright © 2002 Pearson Education, Inc.

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

Page 37: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

37 Copyright © 2002 Pearson Education, Inc.

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.

Page 38: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

38 Copyright © 2002 Pearson Education, Inc.

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;

Page 39: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

39 Copyright © 2002 Pearson Education, Inc.

Subroutine Example Program

1. #!/usr/bin/perl2. 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.

Subroutinedefinition

Page 40: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

40 Copyright © 2002 Pearson Education, Inc.

Would Output The Following …

Page 41: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

41 Copyright © 2002 Pearson Education, Inc.

Passing Arguments 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

Page 42: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

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 argumentSecond

argument

Page 43: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

43 Copyright © 2002 Pearson Education, Inc.

Full Subroutine Example

1. #!/usr/bin/perl2. 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. }

First Argument

SecondArgument

arguments

Page 44: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

44 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

Page 45: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

45 Copyright © 2002 Pearson Education, Inc.

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

Page 46: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

46 Copyright © 2002 Pearson Education, Inc.

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.

return( $result );

Scalar or list variable with avalue to return.

Returns 12 to $result

Page 47: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

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 numbers3. # 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 arg2If bigger

Page 48: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

48 Copyright © 2002 Pearson Education, Inc.

Abbreviated way to check for 0 returned

Can check for 0 returned very conciselyif ( 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 }

PerhapsOutput an error

Page 49: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

49 Copyright © 2002 Pearson Education, Inc.

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

Page 50: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

50 Copyright © 2002 Pearson Education, Inc.

Example Program 1. #!/usr/bin/perl2. 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 OKElse not OK

Page 51: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

51 Copyright © 2002 Pearson Education, Inc.

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

Page 52: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

52 Copyright © 2002 Pearson Education, Inc.

Combining Program Files 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. At least two advantages

» With one file, it is easier to change arguments» It is easier to maintain one file.

Page 53: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

53 Copyright © 2002 Pearson Education, Inc.

Combining Program Files

if ( !param() ) { create_form(); }else { process_form();}

If no parameters, then this isfirst time for program. Callcreate_form to create the

form.

Check to seeif there are any

parameters.

Must be some parameters toprocess so call process_form

Note: Often times will use this to work on one form and “stub” the other. Would build them incrementally.

Page 54: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

54 Copyright © 2002 Pearson Education, Inc.

Consider the following “app” ...

Page 55: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

55 Copyright © 2002 Pearson Education, Inc.

Example Combination Program

1. #!/usr/bin/perl2. 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 form8. print start_html( 'Create Form' );9. print '<FORM ACTION="http://65.108.8.8/cgi-bin/C6/subroutine4.cgi" METHOD="POST">';10. print "<FONT COLOR='BLUE' SIZE=5> How we doing? </FONT>";11. print '<INPUT TEXT TYPE="text" SIZE="15" NAME="doing" >';12. print br, '<INPUT TYPE=SUBMIT VALUE="Click To Submit">';13. print '<INPUT TYPE=RESET VALUE="Erase and Restart">';14. print '</FONT>', end_html;15. }16. sub process_form() {17. # Use this to process the form18. print start_html( 'Received Form ');19. $answ=param('doing');20. print "<FONT COLOR='RED' SIZE=5> You Said ... </FONT>";21. print "$answ", end_html;22.}

Creates initial form.

Receive values and generate next screen.

Page 56: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

56 Copyright © 2002 Pearson Education, Inc.

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 To store in external file:

1.Move subroutine lines to a new file. For example, move outputTableRow sub outputTableRow { print '<TR><TD>One</TD><TD>Two</TD></TR>';

}

Using Subroutines in External Files

Page 57: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

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

Page 58: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

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

Page 59: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

59 Copyright © 2002 Pearson Education, Inc.

Example External Subroutine File

1. sub outputTableRow {2. # PURPOSE: outputs a table row with 2 cols3. # ARGUMENTS: uses $_[0] for first col4. # : uses $_[1] for second col

5. print "<TR><TD>$_[0]</TD><TD>$_[1]</TD></TR>";6. }7. sub specialLine {8. # PURPOSE: Output a line with varible color:9. # ARGUMENTS: $_[0] is the line to output10. # : $_[1] is the line color.11. print "<B><Font COLOR=$_[1] FACE=\"Helvetica\" > $_[0] </FONT></B>";

12. } 13. 1

Page 60: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

60 Copyright © 2002 Pearson Education, Inc.

Example Calling Program

1. #!/usr/bin/perl2. 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 '<TABLE BORDER=1>';7.print '<TH> Num </TH> <TH> Num Cubed </TH>';8.for ( $i=0; $i<3; $i++ ) {9. &outputTableRow( $i, $i**3 );10.}

11. print '</TABLE>', end_html;

Call external routine

Page 61: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

61 Copyright © 2002 Pearson Education, Inc.

Would Output The Following ...

Page 62: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

62 Copyright © 2002 Pearson Education, Inc.

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

Perl uses special operations for adding and deleting hash list items, checking whether hash keys exist, and getting lists of keys and values.

Page 63: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

63 Copyright © 2002 Pearson Education, Inc.

Summary - II 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.

Page 64: 1 Copyright © 2002 Pearson Education, Inc.. 2 Chapter 6 Hashes (Associative Arrays), Environmental…

64 Copyright © 2002 Pearson Education, Inc.

Summary - III 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. 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.