Module 5 Resource

  • October 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Module 5 Resource as PDF for free.

More details

  • Words: 5,162
  • Pages: 31
Chapter 4 - Arrays and Hashes Outline 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 4.12 4.13 4.14 4.15

Introduction Additional Data Types Lists and List Context Arrays Creating and Manipulating an Array Repetition with the for Structure Additional Examples of Creating Arrays Array Manipulation Array Functions List Functions Searching a Sorted Array 4.11.1 Linear Search 4.11.2 Binary Search Introduction to Hashes Creating and Manipulating a Hash Hash-related Functions Internet and World Wide Web Resources

 2001 Prentice Hall, Inc. All rights reserved.

Name of array. (Note that all elements of this array have the same name, c.)

Note: Each element of the array is preceded by $, rather than @, because the individual array elements are scalar values.

$c[ 0 ]

-45

$c[ 1 ]

6

$c[ 2 ]

0

$c[ 3 ]

72

$c[ 4 ]

1543

$c[ 5 ]

-89

$c[ 6 ]

0

$c[ 7 ]

62

$c[ 8 ]

-3

$c[ 9 ]

1

$c[ 10 ]

6453

$c[ 11 ]

78

Position number of the element within array @c.

Fig. 4.1  2001 Prentice Hall, Inc. All rights reserved.

A 12-element array.

Outline

1

#!/usr/bin/perl

2

# Fig. 4.2: fig04_02.pl

3

# Creating and initializing an array with list assignment.

4 5

@array = ( "Hello", 283, "there", 16.439 );

6 7

# display every element of the array

8

$i = 0;

9 10 while ( $i < 4 ) { 11

print "$i

12

++$i;

13 }

0 1 2 3

Create array @array by assigning it a list of values. while structure to display the subscript of each element and its corresponding value.

$array[ $i ]\n";

Displays the element’s value Displays the subscript

Hello 283 there 16.439

 2001 Prentice Hall, Inc. All rights reserved.

Outline

1

#!/usr/bin/perl

2

# Fig. 4.3: fig04_03.pl

3

# Looping through an array with the for repetition structure.

4 5

@array = ( "Hello", 283, "there", 16.439 );

6 7

# display every element of the array

8

for ( $i = 0; $i < 4; ++$i ) {

9

print "$i

$array[ $i ]\n";

10 }

0 1 2 3

Hello 283 there 16.439

Initial value ofcondition Loop-continuation Incrementcontrol of control variable. variable

 2001 Prentice Hall, Inc. All rights reserved.

for structure to display the subscript of each element and its corresponding value.

for keyword

Control variable name

Final value of control variable

for ( $i = 0; $i < 4; ++$i ) Initial value of control variable

Fig. 4.4

Loopcontinuation condition

Increment of control variable

Components of a typical for header.

 2001 Prentice Hall, Inc. All rights reserved.

Establish initial value of control variable counter $i = 0= 1

true $i < 10 Determine if final value of control variable has been reached

Fig. 4.5

false

print "$i\n"; Body of loop (this may be many statements)

Flowcharting a typical for repetition structure.

 2001 Prentice Hall, Inc. All rights reserved.

++$i Increment the control variable

Outline

1

#!/usr/bin/perl

2

# Fig. 4.6: fig04_06.pl

3

# Create an array by referring to nonexistent elements.

4 5

# Create @array with one element by referring to

6

# nonexistent element 0.

7

$array[ 0 ] = "happy";

8

print "@array\n";

Assign string “happy” to $array[ 0 ]. This automatically creates array @array.

9 10 # Add more elements to @array by referring to 11 # nonexistent element 3. There are now 4 elements 12 # in the array. Elements 1 and 2 have undefined values. 13 $array[ 3 ] = "birthday";

Assign string “birthday” to the fourth element of the array. This automatically creates the second and third elements with the value undef.

14 print "@array\n\n"; 15

16 # Loop through the array and replace every undefined 17 # value with an actual value. 18 for ( $i = 0; $i < 4; ++$i ) { 19 20

# if the element is not defined, assign it a value

21

if ( ! defined( $array[ $i ] ) ) {

22 23

$array[ $i ] = "happy"; }

24 } 25 26 print "@array\n"; 27 print @array, "\n";

 2001 Prentice Hall, Inc. All rights reserved.

Use aof for repetition structurethetoarray assign values Print the elements @array. Enclosing name TheThe ifquotes structure assigns the string to to alldisplays undefined elements. logical negation operator (!)“happy” reverses by in double the elements, separated anythe array element that is notreturns defined. Function true if value of adefined condition. spaces. Not enclosing the array name ina value doubleofquotes itselements argumentinisone defined; otherwise, returns displays the long string, with itthe valuesa value of false. concatenated.

happy happy

birthday

happy happy happy birthday happyhappyhappybirthday

 2001 Prentice Hall, Inc. All rights reserved.

Outline

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

#!/usr/bin/perl # Fig. 4.7: fig04_07.pl # Demonstrating the qw and .. operators.

Outline

@array = qw( this is an array of strings ); print "@array\n\n"; @array2 = ( 1 .. 5 ); print "Value\tRunning Total\n";

Operator qw, when passed words separated by spaces, converts the words into a list of strings

for ( $i = 0; $i < 5; ++$i ) { $total += $array2[ $i ]; print( $array2[ $i ], "\t$total\n"); } @array2 = ( 'a' .. 'z' ); print "\n@array2\n";

this is an array of strings Value 1 2 3 4 5

The range operator (..) creates a consecutive range of string or numeric Thevalues. for structure adds each element to Thevariable range operator may bedisplays used the $total andalso then withelement strings.and Thethe range operator running total of the increments the starting value in the elements. range repeatedly until it reaches the ending value in the range.

Running Total 1 3 6 10 15

a b c d e f g h i j k l m n o p q r s t u v w x y z

 2001 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

Outline

#!/usr/bin/perl # Fig. 4.8: fig04_08.pl # Manipulating the length of an array. @array = qw( zero one two three four five six seven eight nine ); # output the number of elements and the last index number print "There are ", scalar( @array ), " elements in \@array.\n"; print "The last index in \@array is $#array.\n\n"; # output the last element in the array print "\@array[ $#array ] is $array[ $#array ].\n\n"; # use negative subscripts to access # elements from the end of the array print "\@array[ -1 ] is $array[ -1 ].\n"; print "\@array[ -4 ] is $array[ -4 ].\n\n";

Function scalar returns the total number of elements in the array.

Assigning The $#array 10 to $#array notation makes determines the the $#array is number used as of thethe subscript new high last index subscript number 10 array. and of @array access of theelements value ofin thethe last increases thetonumber element of the array. array.

$#array = 5; print "@array.\n";

# reduce the Removes number ofallelements to 6in the elements

the array by assigning the empty list to @array. AssigningNegative 5 to $#array makes the new subscripts are used to access the number of elements to 11 high subscript number 5 and deletes the elements of the array from the end of the elements array. at index numbers 6-9.

$#array = 10; print "@array.\n";

# increase

@array = (); # remove all elements in the array print "@array.\n"; print "There are now ", scalar( @array ), " elements in \@array\n";  2001 Prentice Hall, Inc. All rights reserved.

There are 10 elements in @array. The last index in @array is 9. @array[ 9 ] is nine. @array[ -1 ] is nine. @array[ -4 ] is six. zero one two three four five. zero one two three four five . . There are now 0 elements in @array

 2001 Prentice Hall, Inc. All rights reserved.

Outline

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

#!/usr/bin/perl # Fig. 4.9: fig04_09.pl # Demonstrating array slices and list assignment.

Outline

@array = qw( zero one two three four five six seven eight nine ); print "@array\n\n"; List

assignment enables a list of values The brackettooperator, [], to cana be to be assigned listused of scalars. In # display slices of @array An array slice is used on the left side of create a listthis containing thethe specified set example, string “banana” is print "@array[ 1, 3, 5, 7, 9 ]\n"; a list assignment to assign new values to of elementsassigned from an to array. the variable $chiquita print "@array[ 2 .. 6 ]\n\n"; the elements at locations 1, 3, 5, 7, and 9 and the string “pineapple” is of @array. # perform list assignments and display results assigned to the variable $dole. List assignment can also be used to swap ( $chiquita, $dole ) = ( "banana", "pineapple" ); variable values. The values of variables print "\$chiquita = $chiquita\n\$dole = $dole\n"; @array[ 1, 3, 5, 7, 9 ] = qw( 1 3 5 7 9 ); $chiquita and $dole are exchanged. print "@array\n\n"; # use list assignment to swap the values of two variables ( $chiquita, $dole ) = ( $dole, $chiquita ); An array can be used as part of a list on print "After swapping values:\n"; print "\$chiquita = $chiquita\n\$dole = $dole\n\n"; left side of a list assignment. The array

the

receives all remaining initializers in the list assignment on the right side of a list assignment.

# show that an array on the left of a list # receives all remaining initializers in the list on the # right side of a list assignment ( $first, @array2, $second ) = ( 1 .. 8 ); print "\$first = $first\n"; print "\@array2 = @array2\n"; print "\$second = $second\n";  2001 Prentice Hall, Inc. All rights reserved.

zero one two three four five six seven eight nine one three five seven nine two three four five six $chiquita = banana $dole = pineapple zero 1 two 3 four 5 six 7 eight 9 After swapping values: $chiquita = pineapple $dole = banana $first = 1 @array2 = 2 3 4 5 6 7 8 $second =

 2001 Prentice Hall, Inc. All rights reserved.

Outline

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

#!/usr/bin/perl # Fig. 4.10: fig04_10.pl # Demonstrating the push, pop, shift and unshift functions.

Outline

The for structure uses function push to add 5 to the end of

# Use push to insert elements at the end of @array. elements with values 1 through for ( $i = 1; $i <= 5; ++$i ) { @array. push( @array, $i ); # add $i to end of @array print "@array\n"; # display current @array }

Function push receives two arguments: an array and a list elements to be inserted at the end of more elements in @array, pop of each element. the array. @array as a condition. When @array is empty,

# While there are # Note the use of # the condition becomes false; otherwise, it is true. while ( @array ) { Function The for unshift structure uses inserts function an element unshift at theto add $firstTotal += pop( @array ); # remove last element beginning elements with of the values array.1@array through 5 to the beginning of print "@array\n"; # display current @array. } print "\$firstTotal = $firstTotal\n\n";

# Use unshift to insert elementsThe atThe the frontof of condition Function while loop pop the@array. removes while removesloop the theelements last evaluates element from to from true @array ifan for ( $i = 1; $i <= 5; ++$i ) { there andare array, adds elements each returns element inthat the element array to $firstTotal. andand false reduces if the the array Thesize current is of unshift( @array, $i ); # add $i to front of @array empty. contents the array of the byarray one. are displayed in each iteration of print "@array\n"; # display current @array the loop. }

 2001 Prentice Hall, Inc. All rights reserved.

27 # While there are more elements in @array, remove each element 28 # with shift. 29 while ( @array ) { 30

$secondTotal += shift( @array );

# remove first element

31

print "@array\n";

# display current @array

32 } 33 34 print "\$secondTotal = $secondTotal\n"; 1 1 1 1 1 1 1 1 1

2 2 2 2 2 2 2

3 3 4 3 4 5 3 4 3

$firstTotal = 15 1 2 3 4 5 4 3 2 1

1 2 3 4 3 2 1

1 2 1 3 2 1 2 1 1

$secondTotal = 15

 2001 Prentice Hall, Inc. All rights reserved.

Function shift removes and returns the first element of the array.

Outline

Outline

1

#!/usr/bin/perl

2

# Figure 4.11: splice.pl

3

# Demonstrating function splice.

4 5

# create two arrays and display their initial contents

6

@array = ( 0 .. 20 );

7

@array2 = ( A .. F );

8

print "\@array:

9

print "\@array2: @array2\n\n";

@array\n";

Create two arrays and display their contents.

10 11 # replace part of @array with the elements from @array2 12 @replaced = splice( @array, 5, scalar( @array2 ), @array2 ); 13 print "replaced: 14 15 16 17 18 19 20

@replaced\n",

Removes three elements from @array starting with The first argument to function splice is the "with: @array2\n", Function splice removes replaces element 15. The returned list isor stored in @removed. array to modify. The second argument is the offset into the array— "resulting in: @array\n\n"; third argument is the length of the slices of anThe array. Starting from element 5 in @array, all six The fourth argument is a list to replace i.e., the index ofslice the first element to modify in the to modify. elements @array2 replace elements theof specified of the six array. If this of # remove 3 elements, beginning witharray. element 15 of @array slice @array. The listis of replaced returned argument omitted, theelements slice is simply @removed = splice( @array, 15, 3 ); Removes all elements from subscript 8 to the end of from splice stored @replaced. removedisfrom theinarray. print "removed: @removed\n", @array. "leaving:

@array\n\n";

21 22 # remove all elements from element 8 to the end of @array 23 @chopped = splice( @array, 8 ); 24 print "removed:

@chopped\n",

25

@array\n\n";

26

"leaving:

 2001 Prentice Hall, Inc. All rights reserved.

27 # delete all remaining elements 28 splice( @array ); 29 30 unless ( @array ) { 31

Deletes all remaining elements in @array.

print "\@array has no elements remaining\n";

32 }

@array: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 @array2: A B C D E F replaced: 5 6 7 8 9 10 with: A B C D E F resulting in: 0 1 2 3 4 A B C D E F 11 12 13 14 15 16 17 18 19 20 removed: leaving:

15 16 17 0 1 2 3 4 A B C D E F 11 12 13 14 18 19 20

removed: leaving:

D E F 11 12 13 14 18 19 20 0 1 2 3 4 A B C

@array has no elements remaining

 2001 Prentice Hall, Inc. All rights reserved.

Outline

Outline

1

#!/usr/bin/perl

2

# Fig. 4.12: fig04_12.pl

3

# Reversing the elements of an array and

4

# sorting arrays lexically and numerically.

5 6

# create @array with values from 1-10

7

@array = ( 0 .. 9 );

8

@reversed = reverse( @array );

9

print "Original:

10 print "Reversed:

@array\n"; @reversed\n\n";

When passed a list, function sort returns a copy of the list sorted lexically (i.e., in ASCII order); the and reverse the values original list is left unchanged. Function reverse takes a list as an argument and returns a new list with the same contents in reverse order; the original list is left unchanged.

11 12 # create an unsorted array of numbers and sort it Sorts @array2 13 @array2 = ( 100, 23, 9, 75, 5, 10, 2,

numerically by specifying the 50, 7, 96, 1, with 40 ); sorting order { $a <=> $b }.

14 @sortedLexically = sort @array2; 15 @sortedNumerically = sort { $a <=> $b } @array2; 16 print "Unsorted:

@array2\n";

17 print "Lexically:

@sortedLexically\n";

18 print "Numerically: @sortedNumerically\n"; Original: Reversed:

0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 0

Unsorted: 100 23 9 75 5 10 2 50 7 96 1 40 Lexically: 1 10 100 2 23 40 5 50 7 75 9 96 Numerically: 1 2 5 7 9 10 23 40 50 75 96 100

 2001 Prentice Hall, Inc. All rights reserved.

Outline

1

#!/usr/bin/perl

2

# Fig. 4.13: fig04_13.pl

3

# Linear search of an array.

4 5

# populate @array with the even integers from 0 to 198

6

for ( $i = 0; $i < 100; ++$i ) {

7 8

$array[ $i ] = 2 * $i; }

9 10 # prompt the user for a search key 11 print "Enter an integer search key: 12 chomp( $searchKey = <STDIN> ); 13 14 # a boolean value to help determine 15 $found = 0;

# $found is initially

Prompts the user to enter a search key. The for structure populates @array with even integers from 0 to 198. Variable $found is initially set to 0 The for structurethat performs thehas linear (false) to indicate the value not search. The "; condition the for structure is a compound been foundof yet. The logical AND (&&) combines two condition thatoperator tests whether the counter $i is less conditions tosearching create a of more complex condition.and than the number elements in @array when to stop false whether the search key is “not found.”

16

The if structure determines if the current If the searchofkey has been found,the variable element @array contains ) { $found is set to 1value. to exit the loop. $searchKey

17 # use a loop to access every element of @array 18 for ( $i = 0; $i < @array && !$found; ++$i 19 20

# determine if the current element is the search key

21

if ( $array[ $i ] == $searchKey ) {

22

$index = $i;

# store index where it was found

23

$found = 1;

# indicates we should stop looping

24

}

25 }

 2001 Prentice Hall, Inc. All rights reserved.

Outline

26 27 if ( $found ) { 28

# $found == 1

print "Found $searchKey at subscript $index \n";

29 } 30 else { 31

# $found == 0

print "$searchKey not found \n";

32 }

Enter an integer search key: 50 Found 50 at subscript 25

Enter an integer search key: 17 17 not found

 2001 Prentice Hall, Inc. All rights reserved.

Outline

1

#!/usr/bin/perl

2

# Fig. 4.14: fig04_14.pl

3

# Binary search of an array.

4 5

# populate @array with the even integers from 0 to 28

6

for ( $i = 0; $i < 15; ++$i ) {

7 8

$array[ $i ] = 2 * $i; }

9 10 # prompt the user for a search key

Prompts user to and enterpopulate a searchitkey. Createthe @array with even integers from 0 to 28 (a total of 15 elements).

11 print "Enter an integer search key: "; 12 chomp( $searchKey = <STDIN> ); 13 14 # display header string for output 15 print "\n";

# output a blank line

16 17 for ( $i = 0; $i < @array; ++$i ) { 18

print $i < 10 ? "

Displays header of program output.

$i " : " $i ";

19 } 20 21 print "\n", "-" x ( 4 * @array ), "\n"; 22

Defines three elements used in the binary search algorithm.

23 # perform a binary search 24 $found = 0;

# search while !$found

25 $lowIndex = 0;

# start index for search

26 $highIndex = $#array;

# end index for search

27

 2001 Prentice Hall, Inc. All rights reserved.

Outline

28 while ( $lowIndex <= $highIndex && !$found ) { 29 $middleIndex = ( $lowIndex + $highIndex ) / 2; 30 31 # lines 32 through 46 are for output purposes only 32 for ( $i = 0; $i < @array; ++$i ) { 33 if ( $i < $lowIndex || $i > $highIndex ) { For all other variables, that If the Determines control variable’s thecontrol subscript value ofisthe outside The while loop will iterate while 34 print " "; element of the subarray is itrange, the current middle element subarray’s and subscript assigns $lowIndex is less than ortoequal 35 } displayed. then$middleIndex. spaces are output. and the value of 36 elsif ( $i == $middleIndex ) { to $highIndex 37 print $array[ $i ] < 10 ? " $array[ $i ]*" : $found is not true. 38 " $array[ $i ]*"; 39 } If the control variable's value 40 else { 41 print $array[ $i ] < 10 ? " $array[ $i ] " : equals $middleIndex, then the 42 " $array[ $i ] "; middle element of the subarray is 43 } output,equals followed by an asterisk If $searchKey the middle of the TheIffor structure displays the current subarray. 44 } $searchKey is less than the middle (*). the search is complete, so current subarray, 45 element’s $highIndex is assigned $indexvalue, is assigned $middleIndex andthe 46 print "\n"; index one less than $middleIndex. 47 # back to binary searching $found is assigned 1. 48 49 # the following if/elsif/else determines if $searchKey 50 # has been found 51 if ( $searchKey == $array[ $middleIndex ] ) { # match 52 $index = $middleIndex; 53 $found = 1; 54 } 55 elsif ( $searchKey < $array[ $middleIndex ] ) { 56 $highIndex = $middleIndex - 1; # search low end of array 57 }

 2001 Prentice Hall, Inc. All rights reserved.

58 59 60

Outline

else { $lowIndex = $middleIndex + 1; }

For all other $searchKey values, $lowIndex is assigned the index one greater than $middleIndex.

61 } 62 63 # display results 64 if ( $found ) { 65

# $found == 1

print "\nFound $searchKey at subscript $index \n";

66 } 67 else { 68

# search high end of array

# $found == 0

print "\n$searchKey not found \n";

When the loop terminates, the results of the search are displayed.

69 }

Enter an integer search key: 25 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -----------------------------------------------------------0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 16 18 20 22* 24 26 28 24 26* 28 24* 25 not found

 2001 Prentice Hall, Inc. All rights reserved.

Enter an integer search key: 8 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -----------------------------------------------------------0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 0 2 4 6* 8 10 12 8 10* 12 8* Found 8 at subscript 4

Enter an integer search key: 6 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -----------------------------------------------------------0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 0 2 4 6* 8 10 12 Found 6 at subscript 3

 2001 Prentice Hall, Inc. All rights reserved.

Outline

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Outline

#!/usr/bin/perl # Fig. 4.15: fig04_15.pl # Creating and accessing hash elements

# create a hash and output its values Defines a hash by assigning a list to a %hash = ( width => '300', hash variable (%hash). height => '150' ); print "\$hash{ 'width' } = $hash{ 'width' }\n"; Adds a new element to the existing print "\$hash{ 'height' } = $hash{ 'height' }\n\n"; # assigning to $hash{ 'color' print "\$hash{ print "\$hash{ print "\$hash{

a new hash element } = 'blue'; 'width' } = $hash{ 'width' }\n"; 'height' } = $hash{ 'height' }\n"; 'color' } = $hash{ 'color' }\n\n";

hash. Assigning a value to a new key in The first value in this list (width) a hash automatically creates a new is the key of the first element to be element in that hash. A key’s corresponding value be created in the hash, and thecan second accessed bythe preceding the hash name value in list (‘300’) is that with a $ that and enclosing thetokey curly value corresponds thatinkey. braces ({}).

# display a hash with print print "%hash\n"; # no interpolation, unlike with arrays print %hash, "\n"; # difficult to read, no spaces

$hash{ 'width' } = 300 $hash{ 'height' } = 150 $hash{ 'width' } = 300 $hash{ 'height' } = 150 $hash{ 'color' } = blue %hash height150width300colorblue

 2001 Prentice Hall, Inc. All rights reserved.

Outputting thenot hash with print when concatenates allin Hashes are interpolated enclosed thedouble key-value pairs and outputs them as one quotes. long string.

Outline

1

#!/usr/bin/perl

2

# Fig. 4.16: fig04_16.pl

3

# Demonstrating hash slices.

4 5

%romanNumerals = ( one

=> 'I',

6

two

7

three => 'III',

8

four

=> 'IV',

9

five

=> 'V',

10

six

=> 'VI',

11

seven => 'VII',

12

eight => 'VIII',

13

nine

=> 'IX',

14

ten

=> 'X' );

=> 'II',

Creates the hash %romanNumerals Displays of aEnglish hash slice containing wherethe theresults keys are words the values for thethe keys ‘three’, representing numbers from ‘five’ 1 to 10 and and ‘eight’. the values are the roman numerals representing these numbers.

15 16 print "The Roman numerals for three, five and eight are: ", 17

"@romanNumerals{ 'three', 'five', 'eight' }\n";

The Roman numerals for three, five and eight are: III V VIII

 2001 Prentice Hall, Inc. All rights reserved.

Outline

1

#!/usr/bin/perl

2

# Fig. 4.17: fig04_17.pl

3

# Demonstrates hash functions keys, values, each and reverse.

4 5

%presidents = ( George => "Washington",

6

Abe

=> "Lincoln",

7

Thomas => "Jefferson",

8

Harry

=> "Truman" );

9

Assigns the result of function pop to variable $key. The while loop executes until the array is empty.

10 # obtain the list of keys and display each key-value pair 11 @keys = keys( %presidents ); 12

The condition in the loop uses list Function keys obtains a listtoofassign all the$key and assignment print "$key => $presidents{ $key }\n"; Function obtains aThe listresult of values keys in values %presidents. is pair returned $value the key-value } inassigned %presidents. to arrayeach. @keys. Function reverse obtains a list of key-v # display the list of values pairs in which the keys and values are @values = values( %presidents ); reversed. print "\nThe values of the hash are:\n@values\n\n"; Function each is used in the whil to display the reversed key-value p

13 while ( $key = pop( @keys ) ) { 14 15 16 17 18 19 20

21 # reverse the hash and use function each to get each pair 22 print "%presidents with its keys and values reversed\n"; 23 %hash = reverse( %presidents ); 24 25 while ( ( $key, $value ) = each( %presidents ) ) { 26

print "$key => $value\n";

27 }

 2001 Prentice Hall, Inc. All rights reserved.

Harry => Truman Abe => Lincoln Thomas => Jefferson George => Washington The values of the hash are: Washington Jefferson Lincoln Truman %presidents with its keys and values reversed Washington => George Truman => Harry Jefferson => Thomas Lincoln => Abe

 2001 Prentice Hall, Inc. All rights reserved.

Outline

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

Outline

#!/usr/bin/perl # Fig. 4.18: fig04_18.pl # Demonstrating functions delete, exists and defined. %hash = ( Karl Joe Shawn Paul Bill

=> => => => =>

12, 43, 0, 11, undef );

Assigns to @hashKeys all the keys in %hash using function keys.

# obtain the list of hashKeys and display each key-value pair @hashKeys = keys( %hash ); for ( $i = 0; $i < @hashKeys; ++$i ) { print "$hashKeys[ $i ] => $hash{ $hashKeys[ $i ] }\n"; } # delete the element with key 'Joe' from %hash delete( $hash{ 'Joe' } );

Function exists returns true in this context if the key $key is in the hash.

Each key-value pair in %hash is displayed.

# this loop determines if each key exists, is defined and # whether the value for the key evaluates to true or false while ( $key = pop( @hashKeys ) ) { print "\n"; Function delete # determine if a particular key exists if ( exists( $hash{ $key } ) ) { print "$key exists in the hash.\n"; }

 2001 Prentice Hall, Inc. All rights reserved.

removes an element from the hash. In this case, the keyvalue pair for key ‘Joe’ are removed from %hash.

30 31 32

Outline

else { print "$key doesn't exist in the hash.\n"; }

33 34

# determine if the value for the key is defined

35

if ( defined( $hash{ $key } ) ) {

36

print "$key is defined as $hash{ $key }.\n";

37

}

38

else {

39 40

print "$key is undefined.\n"; }

41

Function defined returns true in this context if the key $key is in the hash and its value is defined.

42

# determine if the value for the key is true or false

43

if ( $hash{ $key } ) {

44

print "$key is true.\n";

45

}

46

else {

47 48

print "$key is false.\n"; }

49 }

 2001 Prentice Hall, Inc. All rights reserved.

The if/else structure determines if the value for each $key is true or false when evaluated in boolean context.

Joe => 43 Bill => Karl => 12 Paul => 11 Shawn => 0 Shawn exists in the hash. Shawn is defined as 0. Shawn is false. Paul exists in the hash. Paul is defined as 11. Paul is true. Karl exists in the hash. Karl is defined as 12. Karl is true. Bill exists in the hash. Bill is undefined. Bill is false. Joe doesn't exist in the hash. Joe is undefined. Joe is false.

 2001 Prentice Hall, Inc. All rights reserved.

Outline

Related Documents

Module 5 Resource
October 2019 12
Module 6 Resource 2
October 2019 20
Module 3 Resource
October 2019 11
Module 4 Resource
October 2019 15
Module 2 Resource
October 2019 14