0% found this document useful (0 votes)
4K views31 pages

Perl 04

The document outlines key concepts for arrays and hashes in Perl, including: - Creating arrays using list assignment or by referring to nonexistent elements - Looping through arrays using while and for loops to access and display element values - Components of a typical for loop header like the control variable, initial/final values, and increment - Automatically creating array elements when assigning values to nonexistent indices - Replacing undefined values in an array using an if statement within a for loop

Uploaded by

kalluru charitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4K views31 pages

Perl 04

The document outlines key concepts for arrays and hashes in Perl, including: - Creating arrays using list assignment or by referring to nonexistent elements - Looping through arrays using while and for loops to access and display element values - Components of a typical for loop header like the control variable, initial/final values, and increment - Automatically creating array elements when assigning values to nonexistent indices - Replacing undefined values in an array using an if statement within a for loop

Uploaded by

kalluru charitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 31

Chapter 4 - Arrays and Hashes

Outline
4.1 Introduction
4.2 Additional Data Types
4.3 Lists and List Context
4.4 Arrays
4.5 Creating and Manipulating an Array
4.6 Repetition with the for Structure
4.7 Additional Examples of Creating Arrays
4.8 Array Manipulation
4.9 Array Functions
4.10 List Functions
4.11 Searching a Sorted Array
4.11.1 Linear Search
4.11.2 Binary Search
4.12 Introduction to Hashes
4.13 Creating and Manipulating a Hash
4.14 Hash-related Functions
4.15 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.)

$c[ 0 ] -45
$c[ 1 ] 6
$c[ 2 ] 0
$c[ 3 ] 72
Note: Each element of the
$c[ 4 ] 1543
array is preceded by $, rather
than @, because the individual $c[ 5 ] -89
array elements are scalar $c[ 6 ] 0
values.
$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 A 12-element array.

 2001 Prentice Hall, Inc. All rights reserved.


1 #!/usr/bin/perl Outline
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 Create array @array by
7 # display every element of the array assigning it a list of values.
8 $i = 0; while structure to display the
9 subscript of each element and its
10 while ( $i < 4 ) { corresponding value.
11 print "$i $array[ $i ]\n";
12 ++$i;
13 }
Displays the element’s value
Displays the subscript
0 Hello
1 283
2 there
3 16.439

 2001 Prentice Hall, Inc. All rights reserved.


1 #!/usr/bin/perl Outline
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 );
for structure to display the
6 subscript of each element and its
7 # display every element of the array corresponding value.
8 for ( $i = 0; $i < 4; ++$i ) {
9 print "$i $array[ $i ]\n";
10 }

Initial value ofcondition


Loop-continuation
0 Hello Incrementcontrol
of control variable.
variable
1 283
2 there
3 16.439

 2001 Prentice Hall, Inc. All rights reserved.


for keyword Control variable name Final value of control variable

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

Initial value of Increment of


control variable control variable
Loop-continuation
condition

Fig. 4.4 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 print "$i\n"; ++$i
Body of loop Increment
(this may be many the control
Determine if final value false statements) variable
of control variable has
been reached

Fig. 4.5 Flowcharting a typical for repetition structure.

 2001 Prentice Hall, Inc. All rights reserved.


1 #!/usr/bin/perl Outline
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"; Assign string “happy” to $array[ 0 ].
8 print "@array\n"; 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
14 print "@array\n\n";
of the array. This automatically creates the second
15
and third elements with the value undef.
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 $array[ $i ] = "happy"; Use aof for repetition structurethetoarray
assignname
values
23 }
Print the elements @array. Enclosing
TheThe
in doubleif structure
logical
quotes assigns
to alldisplays
undefined
negation the the string
elements.
operator
elements,(!)“happy”
reverses by
separated to
24 } anythe
array element that is notreturns
defined.
25 spaces. Not Function
value of adefined
enclosing condition.
the array name ina value
doubleofquotes
true if
26 print "@array\n"; displays theitselements
argumentinisone defined; otherwise,
long string, with itthe
returns
valuesa
27 print @array, "\n"; value of false.
concatenated.
 2001 Prentice Hall, Inc. All rights reserved.
happy Outline
happy birthday
 
happy happy happy birthday
happyhappyhappybirthday

 2001 Prentice Hall, Inc. All rights reserved.


1 #!/usr/bin/perl Outline
2 # Fig. 4.7: fig04_07.pl
3 # Demonstrating the qw and .. operators.
4
5 @array = qw( this is an array of strings );
6 print "@array\n\n";
7
8 @array2 = ( 1 .. 5 ); Operator qw, when passed words
9 print "Value\tRunning Total\n"; separated by spaces, converts the words
10 into a list of strings
11 for ( $i = 0; $i < 5; ++$i ) {
12 $total += $array2[ $i ];
The range operator (..) creates a
13 print( $array2[ $i ], "\t$total\n");
consecutive range of string or numeric
14 }
15 Thevalues.
for structure adds each element to
16 @array2 = ( 'a' .. 'z' ); Thevariable
range operator
$total mayandalso
thenbedisplays
used the
17 print "\n@array2\n"; withelement
strings.and
Thethe
range operator
running total of the
increments
elements.the starting value in the
this is an array of strings range repeatedly until it reaches the
  ending value in the range.
Value Running Total
1 1
2 3
3 6
4 10
5 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 #!/usr/bin/perl Outline
2 # Fig. 4.8: fig04_08.pl
3 # Manipulating the length of an array.
4
5 @array =
6 qw( zero one two three four five six seven eight nine );
7
8 # output the number of elements and the last index number
9 print "There are ", scalar( @array ),
10 " elements in \@array.\n";
11 print "The last index in \@array is $#array.\n\n"; Function scalar returns the
12
total number of elements in the
13 # output the last element in the array
array.
14 print "\@array[ $#array ] is $array[ $#array ].\n\n";
15
16 # use negative subscripts to access Assigning
The $#array
10 to $#array
notation
makes
determines
the the
17 # elements from the end of the array new$#array
high
last indexis number
used
subscript as of
thethe
number subscript
10 and of
array.
18 print "\@array[ -1 ] is $array[ -1 ].\n"; @array
increases thetonumber
access of
theelements
value ofin
thethe
last
19 print "\@array[ -4 ] is $array[ -4 ].\n\n"; element of the array.
array.
20
21 $#array = 5; # reduce the Removes
number ofallelements to 6in
the elements the array by
22 print "@array.\n";
assigning the empty list to @array.
23 AssigningNegative
5 to $#array makes
subscripts the new
are used to access
24 $#array = 10; # increase high subscript
the number number
of elements 5
to 11 and deletes the
elements of the array from the end of the
25 print "@array.\n"; elements array.
at index numbers 6-9.
26
27 @array = (); # remove all elements in the array
28 print "@array.\n";
29 print "There are now ", scalar( @array ),
30 " elements in \@array\n";
 2001 Prentice Hall, Inc. All rights reserved.
There are 10 elements in @array. Outline
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.


1 #!/usr/bin/perl Outline
2 # Fig. 4.9: fig04_09.pl
3 # Demonstrating array slices and list assignment.
4
5 @array =
6 qw( zero one two three four five six seven eight nine );
7 print "@array\n\n"; List assignment enables a list of values
8
The brackettooperator, [], to
be assigned cana list
be used to
of scalars. In
9 # display slices of @array An array
create a listthis slice
containing is used
thethe on
specified the left
set side of
10 print "@array[ 1, 3, 5, 7, 9 ]\n";
example, string “banana” is
a list assignment
of elementsassigned
from an to
array. to assign new values to
11 print "@array[ 2 .. 6 ]\n\n"; the variable $chiquita
the elements at locations 1, 3, 5, 7, and 9
12 and the string “pineapple” is
of @array.
13 # perform list assignments and display results assigned to the variable $dole.
14 ( $chiquita, $dole ) = ( "banana", "pineapple" ); List assignment can also be used to swap
15 print "\$chiquita = $chiquita\n\$dole = $dole\n"; variable values. The values of variables
16 @array[ 1, 3, 5, 7, 9 ] = qw( 1 3 5 7 9 ); $chiquita and $dole are exchanged.
17 print "@array\n\n";
18
19 # use list assignment to swap the values of two variables
20 ( $chiquita, $dole ) = ( $dole, $chiquita );
21 print "After swapping values:\n"; An array can be used as part of a list on the
22 print "\$chiquita = $chiquita\n\$dole = $dole\n\n";
left side of a list assignment. The array
23
receives all remaining initializers in the list
24 # show that an array on the left of a list assignment
25 # receives all remaining initializers in the listononthe right side of a list assignment.
the
26 # right side of a list assignment
27 ( $first, @array2, $second ) = ( 1 .. 8 );
28 print "\$first = $first\n";
29 print "\@array2 = @array2\n";
30 print "\$second = $second\n";
 2001 Prentice Hall, Inc. All rights reserved.
  Outline
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.


1 #!/usr/bin/perl Outline
2 # Fig. 4.10: fig04_10.pl
3 # Demonstrating the push, pop, shift and unshift functions.
4
5 # Use push to insert elements at the end of @array.
6 for ( $i = 1; $i <= 5; ++$i ) {
7 push( @array, $i ); # add $i to end of @array
8 print "@array\n"; # display current @array
9 }
10 TheFunction
for structure
pushuses
receives
function
two push
arguments:
to addan array
11 # While there are more elements in elements
and a with
@array, list
pop ofvalues
elements
each 1 through
to be inserted
element. 5 to the at
end
theofend of
12 # Note the use of @array.
the array.
@array as a condition. When @array is empty,
13 # the condition becomes false; otherwise, it is true.
14 while ( @array ) {
15
The
Function
for structure
unshift uses
inserts
$firstTotal += pop( @array ); # remove last element
function
an element
unshiftat the
to add
16 print "@array\n"; elements
beginning
with
of the
# display values
array.
current1 through
@array 5 to the beginning of
17 } @array.
18
19 print "\$firstTotal = $firstTotal\n\n";
20
21 # Use unshift to insert elementsThe
atThe
condition
Function
thewhile
frontofloop
pop
the@array.
of removes
while
removesloop
the
theelements
last
evaluates
element
from
to from
true
@array
ifan
22 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
23 unshift( @array, $i ); # add
empty. $i
contents to
the array front
of the
byarray of @array
one. are displayed in each iteration of
24 print "@array\n"; # display current @array
the loop.
25 }
26

 2001 Prentice Hall, Inc. All rights reserved.


27 # While there are more elements in @array, remove each element Outline
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 2 Function shift removes and returns the
1 2 3
first element of the array.
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
 
$firstTotal = 15
 
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
 
$secondTotal = 15
 2001 Prentice Hall, Inc. All rights reserved.
1 #!/usr/bin/perl Outline
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: @array\n"; Create two arrays and display their
9 print "\@array2: @array2\n\n"; contents.
10
11 # replace part of @array with the elements from @array2
12 @replaced = splice( @array, 5, scalar( @array2 ), @array2 );
13 print "replaced: @replaced\n",
Removes three elements from @array starting with
14 "with: @array2\n",
The first argument to function splice is the
Function
element
array splice
15. The
to modify. returnedremoves
list isor replaces
stored in @removed.
15 "resulting in: @array\n\n"; The second argument
slices of anThe array. is the offset into the
third argument is the length array— of the
Starting Thefrom element
fourth
i.e., the index ofslice 5
argument
the first in @array,
is a list toall
element to modify in the six
replace
16 to modify.
17 # remove 3 elements, beginning witharray.
elements
element 15 theof
of
@array2
specified replace six elements of
@array slice of the array. If this
18 @removed = splice( @array, 15, 3 );
@array. The listis of
argument replaced
omitted, theelements returned
slice is simply
Removes all elements from subscript 8 to the end of
19 print "removed: @removed\n",
from splice
removedisfrom storedtheinarray.
@replaced.
@array.
20 "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 "leaving: @array\n\n";
26
 2001 Prentice Hall, Inc. All rights reserved.
27 # delete all remaining elements Outline
28 splice( @array );
Deletes all remaining elements in
29
@array.
30 unless ( @array ) {
31 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: 15 16 17
leaving: 0 1 2 3 4 A B C D E F 11 12 13 14 18 19 20
 
removed: D E F 11 12 13 14 18 19 20
leaving: 0 1 2 3 4 A B C
 
@array has no elements remaining

 2001 Prentice Hall, Inc. All rights reserved.


1 #!/usr/bin/perl Outline
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 and reverse the values
7 @array = ( 0 .. 9 );
8 @reversed = reverse( @array );
When
Sorts Function
passedreverse
@array2 anumerically
list, function
takes
bysort
aspecifying
list asreturns
an argument
thea copy of
9 print "Original: @array\n";
theand
sortinglist returns
sorted
order withlexically
a{new$a list
(i.e.,
<=> with
$binthe
ASCII
}.sameorder);
contents
thein
10 print "Reversed: @reversed\n\n"; original
reverselistorder;
is leftthe
unchanged.
original list is left unchanged.
11
12 # create an unsorted array of numbers and sort it
13 @array2 = ( 100, 23, 9, 75, 5, 10, 2, 50, 7, 96, 1, 40 );
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: 0 1 2 3 4 5 6 7 8 9
Reversed: 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.


1 #!/usr/bin/perl Outline
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 $array[ $i ] = 2 * $i;
8 } Prompts the user to enter a search key.
9
The for structure populates @array with
10 # prompt the user for a search key
even integers
Variable $found from 0 to 198.
is initially set to 0
11 print "Enter an integer search key: "; The for
(false) structurethat
to indicate performs
the value thehas
linear
not search. The
12 chomp( $searchKey = <STDIN> ); condition
been foundof the for structure is a compound
yet.
13 The logical
conditionANDthatoperator (&&) combines
tests whether the countertwo
$i is less
14 # a boolean value to help determine conditions
when than
to tosearching
the
stop create a of
number more complex
elements condition.and
in @array
15 $found = 0; # $found is initially false whether the search key is “not found.”
16
17 # use a loop to access every element of @array
The if structure determines if the current
If the searchofkey
element has been
@array found,the
contains variable
18 for ( $i = 0; $i < @array && !$found; ++$i ) {
19
$found is set to 1value.
$searchKey to exit the loop.
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.


26 Outline
27 if ( $found ) { # $found == 1
28 print "Found $searchKey at subscript $index \n";
29 }
30 else { # $found == 0
31 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.


1 #!/usr/bin/perl Outline
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 $array[ $i ] = 2 * $i;
Prompts
Createthe user to and
@array enterpopulate
a searchitkey.
with
8 }
9 even integers from 0 to 28 (a total of
10 # prompt the user for a search key 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 ) { Displays header of program output.
18 print $i < 10 ? " $i " : " $i ";
19 }
20
Defines three elements used in the binary
21 print "\n", "-" x ( 4 * @array ), "\n";
search algorithm.
22
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.
28 while ( $lowIndex <= $highIndex && !$found ) { Outline
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 ) { If theFor all other
Determines
control control
variable’s
the variables,
subscript
value ofis the that
outside
34 print " "; The
element while
of the loop will
subarray iterate
is while
35 }
the current
middle element
subarray’s
$lowIndex and
issubscript
assigns
less than it range,
ortoequal
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 }
40 else { If the control variable's value
41 print $array[ $i ] < 10 ? " $array[ $i ] " : equals $middleIndex, then the
42 " $array[ $i ] "; middle element of the subarray is
43 }
If $searchKeyoutput,equals
followedthe by an asterisk
middle of the
44 } TheIffor structure
$searchKey displays
is lessthe current
than the subarray.
middle
45
(*). the search is complete, so
current subarray,
element’s
$indexvalue, $highIndex
is assigned $middleIndex is assigned andthe
46 print "\n";
47 # back to binary searching index one less
$found than $middleIndex.
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 else { Outline
59 $lowIndex = $middleIndex + 1; # search high end of array
60 }
61 } For all other $searchKey values,
62 $lowIndex is assigned the index one
63 # display results greater than $middleIndex.
64 if ( $found ) { # $found == 1
65 print "\nFound $searchKey at subscript $index \n";
66 }
67 else { # $found == 0 When the loop terminates, the results of
68 print "\n$searchKey not found \n";
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 Outline
 
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.


1 #!/usr/bin/perl Outline
2 # Fig. 4.15: fig04_15.pl
3 # Creating and accessing hash elements
4
5 # create a hash and output its values Defines a hash by assigning a list to a
6 %hash = ( width => '300',
hash variable (%hash).
7 height => '150' );
8 print "\$hash{ 'width' } = $hash{ 'width' }\n";
Adds a new element to the existing
9 print "\$hash{ 'height' } = $hash{ 'height' }\n\n";
hash.
TheAssigning
first valuea invalue
this to
lista (width)
new key in
10
a hash
is theautomatically
key of the first creates
elementa newto be
11 # assigning to a new hash element
12 $hash{ 'color' } = 'blue'; Aelement
key’s
created in in
that
thehash.
corresponding
hash, value
and the can be
second
13 print "\$hash{ 'width' } = $hash{ 'width' }\n"; accessed
value by preceding
in the the hash
list (‘300’) name
is that
14 print "\$hash{ 'height' } = $hash{ 'height' }\n"; withvalue
a $ and
thatenclosing
corresponds the to
keythat
in key.
curly
15 print "\$hash{ 'color' } = $hash{ 'color' }\n\n"; braces ({}).
16
17 # display a hash with print
18 print "%hash\n"; # no interpolation, unlike with arrays
19 print %hash, "\n"; # difficult to read, no spaces

$hash{ 'width' } = 300


$hash{ 'height' } = 150 Outputting
Hashes arethenot
hash with print when
interpolated concatenates
enclosedallin
  thedouble
key-value pairs and outputs them as one
quotes.
$hash{ 'width' } = 300 long string.
$hash{ 'height' } = 150
$hash{ 'color' } = blue
 
%hash
height150width300colorblue

 2001 Prentice Hall, Inc. All rights reserved.


1 #!/usr/bin/perl Outline
2 # Fig. 4.16: fig04_16.pl
3 # Demonstrating hash slices.
4
5 %romanNumerals = ( one => 'I',
6 two => 'II',
7 three => 'III',
8 four => 'IV',
Creates the hash %romanNumerals
9 five => 'V', Displays
wherethe
theresults of aEnglish
keys are hash slice containing
words
10 six => 'VI', the values for thethe
representing keys ‘three’,
numbers from ‘five’
1 to 10
11 seven => 'VII', and and
‘eight’.
the values are the roman numerals
12 eight => 'VIII', representing these numbers.
13 nine => 'IX',
14 ten => 'X' );
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.


1 #!/usr/bin/perl Outline
2 # Fig. 4.17: fig04_17.pl
3 # Demonstrates hash functions keys, values, each and reverse.
4
5 %presidents = ( George => "Washington",
6 Abe => "Lincoln",
Assigns the result of function pop to
7 Thomas => "Jefferson",
variable $key. The while loop executes
8 Harry => "Truman" );
until the array is empty.
9
10 # obtain the list of keys and display each key-value pair
11 @keys = keys( %presidents );
12
13 while ( $key = pop( @keys ) ) { Function keys obtains a list of all the
14 print "$key => $presidents{ $key }\n"; Function
keys in values obtains aThe
%presidents. list result
of values
is
15 } inassigned
%presidents.
to array @keys.
16
Function reverse obtains a list of key-value
17 # display the list of values
pairs in which the keys and values are
18 @values = values( %presidents );
19
reversed.
print "\nThe values of the hash are:\n@values\n\n";
20
Function The
each condition
is used in
in the
the while
loop uses
loop
list
21 # reverse the hash and use function each to get each pair
to displayassignment
the reversedtokey-value
assign $key
pairs.
and
22 print "%presidents with its keys and values reversed\n";
$value the key-value pair returned by
23 %hash = reverse( %presidents );
each.
24
25 while ( ( $key, $value ) = each( %presidents ) ) {
26 print "$key => $value\n";
27 }
 2001 Prentice Hall, Inc. All rights reserved.
Harry => Truman Outline
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.


1 #!/usr/bin/perl Outline
2 # Fig. 4.18: fig04_18.pl
3 # Demonstrating functions delete, exists and defined.
4
5 %hash = ( Karl => 12,
6 Joe => 43, Assigns to @hashKeys all the keys in
7 Shawn => 0, %hash using function keys.
8 Paul => 11,
9 Bill => undef );
10
11 # obtain the list of hashKeys and display each key-value pair
12 @hashKeys = keys( %hash );
13 Function exists returns true in
14 for ( $i = 0; $i < @hashKeys; ++$i ) { this context if the key $key is in
15 print "$hashKeys[ $i ] => $hash{ $hashKeys[ $i ] }\n"; the hash.
16 }
17 Each key-value pair in %hash is
18 # delete the element with key 'Joe' from %hash displayed.
19 delete( $hash{ 'Joe' } );
20
21 # this loop determines if each key exists, is defined and
22 # whether the value for the key evaluates to true or false
23 while ( $key = pop( @hashKeys ) ) {
24 print "\n"; Function delete removes an element
25 from the hash. In this case, the key-
26 # determine if a particular key exists
value pair for key ‘Joe’ are removed
27 if ( exists( $hash{ $key } ) ) {
28 print "$key exists in the hash.\n";
from %hash.
29 }

 2001 Prentice Hall, Inc. All rights reserved.


30 else { Outline
31 print "$key doesn't exist in the hash.\n";
32 }
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 { Function defined returns true in this
39 print "$key is undefined.\n"; context if the key $key is in the hash
40 }
and its value is defined.
41
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 { The if/else structure determines if the
47 print "$key is false.\n"; value for each $key is true or false when
48 } evaluated in boolean context.
49 }

 2001 Prentice Hall, Inc. All rights reserved.


Joe => 43 Outline
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.

You might also like