Docstoc

Perl_04_Arrays and Hashes

Document Sample
Perl_04_Arrays and Hashes Powered By Docstoc
					                   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           $c[ 5 ]               -89
             individual array elements            $c[ 6 ]                  0
             are scalar 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 condition
                              Loop-continuationof
0    Hello                Increment of control variable.
                                  control 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

                                           $i = =
                                        counter 0 1




                                                          true
                                          $i < 10                  print "$i\n";             ++$i
                                                                 Body of loop          Increment
                                                                 (this may be many     the control
                    Determine if final            false          statements)           variable
                    value 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 for repetition structure to assign values
23      }
                                                  Print the elementsaof @array. Enclosing the array name
                                                         The structure assigns the string “happy”
                                                      The iflogical negation operator (!) reverses to
24 }
                                                                 to all undefined elements,
                                                  in double quotes displays the elements. separated by
25                                                       the value of adefined defined.
                                                      any array element the is notname a double quotes
                                                  spaces. Not enclosing thatarrayreturnsin value of true if
                                                             Function condition.
26 print "@array\n";                                         its argument is defined; otherwise, the values
                                                  displays the elements in one long string, with it returns a
27 print @array, "\n";                                       value
                                                  concatenated. of false.
 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");
14   }
                                                          consecutive range of string or numeric
15                                                    Thevalues.
                                                           for structure adds each element to
16   @array2 = ( 'a' .. 'z' );                    Thevariable $total and then displays the
                                                       range operator may also be used
17   print "\n@array2\n";                             element The range operator
                                                  with strings.and the running total of the
                                                  increments the starting value in the
                                                      elements.
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
14   print "\@array[ $#array ] is $array[ $#array ].\n\n";
                                                                        array.
15
16   # use negative subscripts to access                      The 10 to $#array makes the
                                                       Assigning$#array notation determines the
17   # elements from the end of the array                 $#array is used as of 10 and
                                                              last subscript number subscript
                                                       new high index number thethe array. of
18   print "\@array[ -1 ] is $array[ -1 ].\n";            @array number the value of the last
                                                       increases theto access of elements in the
19   print "\@array[ -4 ] is $array[ -4 ].\n\n";          element of the array.
                                                       array.
20
21   $#array = 5;                         number of the elements in
                            # reduce the Removes allelements to 6      the array by
22   print "@array.\n";
                                          assigning the empty list to @array.
23                                             Assigning 5 to $#array makes used to access
                                                        Negative subscripts are the new
24   $#array = 10;          # increase         high of elements of the array from the end of
                                                         elements to 11
                                         the numbersubscript number 5 and deletes the
25   print "@array.\n";
                                                        at array.
                                               elements theindex 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
 8
                                                   The bracket operator, [], can be to a list of
                                                                values to be assigned used to
 9   # display slices of @array
10   print "@array[ 1, 3, 5, 7, 9 ]\n";
                                                                  array
                                                             Ancontaining theused on the left side of
                                                   create a listscalars. slice is example, the string
                                                                          In this specified set
11   print "@array[ 2 .. 6 ]\n\n";
                                                             a list assignment assigned to thevalues to
                                                   of elements“banana” is to assign new variable
                                                                 from an array.
                                                             the elements at locations 1, 3, 5, 7, and 9
                                                                $chiquita and the string
12
                                                             of @array.
13   # perform list assignments and display results             “pineapple” is assigned to the
14   ( $chiquita, $dole ) = ( "banana", "pineapple" );    List assignment can also be used to swap
                                                                variable $dole.
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
24 # show that an array on the left of a
                                                        receives all remaining initializers in the list
                                              list assignment
25 # receives all remaining initializers                on the right side of a list assignment.
                                              in the list on 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                                                  for structure receives two arguments: an
                                                TheFunction pushuses function push to add array
11   # While there are                             and a pop each element.
                                                 @array, list of elements to be 5 to the end of
                               more elements in elements with values 1 throughinserted at the end of
12   # Note the use of                          @array.
                                                   the When
                               @array as a condition. array. @array is empty,
13   # the condition becomes false; otherwise, it is true.
14   while ( @array ) {
15
                                     Function unshift inserts an element at the
                                    The for structure uses function unshift to add
        $firstTotal += pop( @array ); # remove last element
16      print "@array\n";            beginning of values 1 @array
                                    elements with the array.through 5 to the beginning of
                                       # display current
17   }                              @array.
18
19   print "\$firstTotal = $firstTotal\n\n";
20
21                                           while the removes
                                        TheFunction pop while the evaluates to true an
     # Use unshift to insert elements at condition ofof @array. loopelements from @array
                                     The the front loop removes the last element fromif
22                                           adds returns that to $firstTotal. The current
     for ( $i = 1; $i <= 5; ++$i ) { there are elements in the element and reduces the size of
                                        and array, each elementarray and false if the array is
23      unshift( @array, $i );          # add array by one. are displayed in each iteration of
                                        contents to front
                                     empty.the$iof the arrayof @array
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
1   2   3 4
                                                  first element of the array.
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",
                                         Removesargument to function @array starting with
                                         The first three elements from splice is the
14         "with:         @array2\n",       Function splice removes stored in @removed.
                                         element modify. returned list isor replaces
                                         array to 15. The
           "resulting in: @array\n\n"; The second argument is the offset intothe length of the
15                                          slices of anThe third argument is the
                                                         array.
16                                     array—i.e.,The indexto modify. @array,to six
                                                    the fourthof the in element replace
                                            Starting from element 5first is a list toall
                                                        slice argument
17                                     modify in 15 of @array2 replace six elements of
                                            elements of @arrayslice of the array. If this
                                                   the specified
     # remove 3 elements, beginning with element the array.
18
                                            @array. The list of replaced elementssimply
                                                   argument is omitted, the slice       returned
     @removed = splice( @array, 15, 3 ); Removes all elements from subscript is to the end of
                                            from splice is stored in @replaced.      8
19   print "removed:      @removed\n",             removed from the array.
                                           @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 );                 Sorts Function reverse takes sortas an argument of
                                                       When passed a list, function a list returns a copy
                                                          @array2 numerically by specifying the
9    print "Original:             @array\n";                 order with new <=> $b }.
                                                       theand sorted a{ $a list with the same contents
                                                    sortinglist returns lexically (i.e., in ASCII order); thein
10 print "Reversed:               @reversed\n\n";         reverse order; unchanged.
                                                       original list is leftthe 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 $found is initially set
                                                       Variableintegers from 0 to 198. to 0
11 print "Enter an integer search key:            ";    The for structure performs the linear
                                                       (false) to indicate that the value has not search. The
12 chomp( $searchKey = <STDIN> );                      been foundof the for structure is a compound
                                                        condition yet.
13                                                 The logical AND operator (&&) combines two is less
                                                        condition that tests whether the counter $i
14 # a boolean value to help determine            when to stop searching elements in @array and
                                                        than the create a more complex condition.
                                                   conditions to number of
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
18 for ( $i = 0; $i < @array && !$found; ++$i
                                                              element of @array contains variable
                                                          If the search key has been found,the
                                                          ) {
19
                                                          $found is set to 1 to exit the loop.
                                                              $searchKey value.
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;
                                                              Create @array enter a search with
                                                            Prompts the user to and populate itkey.
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 ) {           For all other control variables,
                                                             Determines the loop will iterate that
                                                                The while subscript is outside
                                                        If the control variable’s valueof the while
34          print "    ";                                     element of the subarray is it to
35       }
                                                             middle subarray’s subscript or equal
                                                        the current element andless than range,
                                                                $lowIndex is assigns
                                                              displayed. output.
                                                             $middleIndex. and the value of
                                                        then spaces are
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
42                                    " $array[ $i ] ";        the middle element of the
43       }
44    }                                      TheIf If $searchKeyis lessoutput, followedthe an
                                                               subarray is
                                                  for structure displays thethe the middle by
                                                   $searchKey
                                                                       equals current subarray.
                                                                             than
                                                                                  middle of
45
                                                               asterisk (*).
                                                   current subarray, the search is complete, so
                                                 element’s value, $highIndex is assigned the
                                                   $index is assigned $middleIndex and
46    print "\n";
47    # back to binary searching                   $found is than $middleIndex.
                                                 index one less 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";
                                                                        The first value value list (width)
                                                                     hash. Assigning a in thisto a new key in
10
11   # assigning to       a new hash element
                                                                     a hash automatically creates a new be
                                                                        is the key of the first element to
12   $hash{ 'color'       } = 'blue';                               A key’s corresponding value can be
                                                                        created that hash.
                                                                     element in in the hash, and the second
13   print "\$hash{       'width' } = $hash{ 'width' }\n";              value in preceding the hash that
                                                                    accessed by the list (‘300’) is name
14   print "\$hash{       'height' } = $hash{ 'height' }\n";        with a $ and enclosing the to that key.
                                                                        value that corresponds key in 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                              Hashes the hash with print concatenates all
                                                  Outputtingare not interpolated when enclosed in
                                                      key-value pairs
                                                  thedouble quotes. and outputs them as one
$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',
                                                        where the keys of English words
                                                     Displays the resultsare a hash slice
10                              six      => 'VI',    containing the values for the keys ‘three’,
                                                        representing the numbers from 1 to 10
11                              seven => 'VII',      ‘five’ and ‘eight’.
                                                        and 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 values obtains a list result is
                                                    keys in %presidents. The of values
15   }                                               %presidents.
                                                  inassigned to array @keys.
16
                                               Function reverse obtains a list of key-value
17   # display the list of values
18   @values = values( %presidents );
                                               pairs in which the keys and values are
19
                                               reversed.
     print "\nThe values of the hash are:\n@values\n\n";
20
                                                                      each is used in the loop uses list
                                                            Function The condition in the while loop
21 # reverse the hash and use function each to get each pair
                                                                       the reversed assign $key and
                                                            to displayassignment tokey-value pairs.
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.

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:1
posted:2/10/2012
language:
pages:31