Download presentation
Presentation is loading. Please wait.
1
Chapter 13 - References Outline 13.1 Introduction 13.2 References 13.3 References to Nonscalars 13.4 Anonymous Structures 13.5 Closures 13.6 References as Function Arguments 13.7 Nested Data Structures 13.8 Garbage Collection and Circular References 13.9 Symbolic References Typeglobs Referencing Filehandles Uses for References Internet and World Wide Web Resources
2
13.2 References Reference Hard References Symbolic References
Indirectly points to value Scalars that tell program where to find another value Hard References Refer directly to a value in memory Not a variable Unary backslash operator (\) Symbolic References Soft references Hold the name of the variable to which they refer to
3
$reference is a hard reference to scalar $variable
1 #!/usr/bin/perl 2 # Fig. 13.1: fig13_01.pl 3 # Demonstrates creating and dereferencing a reference. 4 5 use strict; 6 use warnings; 7 8 my $variable = 10; 9 my $reference = \$variable; 10 11 print( "\$variable = $variable\n" ); 12 print( "\$reference = $reference\n" ); 13 print( "\$\$reference = $$reference\n" ); 14 $variable++; 15 print( "\$variable = $variable\n" ); 16 print( "\$reference = $reference\n" ); 17 print( "\$\$reference = $$reference\n" ); 18 $$reference++; 19 print( "\$variable = $variable\n" ); 20 print( "\$reference = $reference\n" ); 21 print( "\$\$reference = $$reference\n" ); Fig13_01.pl $reference is a hard reference to scalar $variable Prints the value of $variable Prints the value of the reference Prints the value that the reference points to Adds 1 to $variable will also affect the value $reference points to Adds 1 to $$reference, will also change the value of $variable
4
Fig13_01.pl Program Output $variable = 10
$reference = SCALAR(0x8a31018) $$reference = 10 $variable = 11 $$reference = 11 $variable = 12 $$reference = 12 Fig13_01.pl Program Output
5
13.3 References to Nonscalars
Nonscalar References Same syntax as a a reference to a scalar Nested references Two ways of dereferencing Arrow operator (->) With arrays $$reference [element] $reference->[element] @$reference is used to access the whole array
6
13.3 References to Nonscalars
With hashes $$reference{ ‘key’ } $reference->{ ‘key’ } %$reference is used to access the whole hash Direct dereferencing With functions &$function(arguments) $function->(arguments)
7
Creates a reference to an array
1 #!/usr/bin/perl 2 # Fig. 13.2: fig13_02.pl 3 # Demonstrates how to use references to arrays and hashes. 4 5 use strict; 6 use warnings; 7 8 = qw( duck pig horse rooster cow ); 9 my %hash = ( duck => "quack", pig => "oink", horse => "neigh", rooster => "cock-a-doodle-doo", cow => "moo" ); 14 17 18 sub returnReference 19 { 20 return 21 } 22 24 23 print( ); 27 print 28 ( "\${returnReference()}[ 1 ] = ${returnReference()}[ 1 ]\n\n" ); 29 16 my $hashReference = \%hash; 15 my $arrayReference = 26 print( "\$arrayReference->[ 1 ] = $arrayReference->[ 1 ]\n" ); 25 print( "\$\$arrayReference[ 1 ] = $$arrayReference[ 1 ]\n" ); Fig13_02.pl Creates a reference to an array Creates a reference to a hash Two different ways to access the same array element Dereferences the value that is returned from the returnReference function Dereferences the entire array
8
Accessing the hash values of the reference Fig13_02.pl
30 print( "\$\$hashReference{ duck } = $$hashReference{ duck }\n" ); 31 print 32 ( "\$hashReference->{ duck } = $hashReference->{ duck }\n\n" ); 33 34 foreach ( keys( %$hashReference ) ) { 35 print( "The $_ goes $hashReference->{ $_ }.\n" ); 36 } Accessing the hash values of the reference Fig13_02.pl Program Output Dereferencing the value using the arrow operator Dereferencing the entire hash table duck pig horse rooster cow $$arrayReference[ 1 ] = pig $arrayReference->[ 1 ] = pig ${returnReference()}[ 1 ] = pig $$hashReference{ duck } = quack $hashReference->{ duck } = quack The cow goes moo. The pig goes oink. The duck goes quack. The horse goes neigh. The rooster goes cock-a-doodle-doo.
9
Creates a reference to function
1 #!/usr/bin/perl 2 # Fig. 13.3: fig13_03.pl 3 # Using function references 4 5 use strict; 6 use warnings; 7 8 my $functionReference = \&function; 9 &$functionReference( "a", "bunch", "of", "words" ); 10 $functionReference->( "some", "other", "words" ); 11 12 sub function 13 { 14 print( "I have been called as arguments.\n" ); 15 } Fig13_03.pl Program Output Creates a reference to function Two different ways to call a referenced function I have been called with a bunch of words as arguments. I have been called with some other words as arguments.
10
Creates reference to $variable
1 #!/usr/bin/perl 2 # Fig. 13.4: fig13_04.pl 3 # References to references 4 5 use warnings; 6 use strict; 7 8 my $variable = 5; 9 my $reference1 = \$variable; 10 print( "$variable, $reference1, $$reference1\n" ); 11 my $reference2 = \$reference1; 12 print( "$variable, $reference1, $$reference1, $reference2, ", "$$reference2, $$$reference2\n" ); 14 my $reference3 = \\\\$variable; 15 print( "$reference3, $$reference3, $$$reference3,\n", " $$$$reference3, $$$$$reference3\n" ); Fig13_04.pl Program Output Creates reference to $variable Creates a reference to a reference Creates 4 levels of indirection Need to get through all the levels of indirection 5, SCALAR(0x8a31018), 5 5, SCALAR(0x8a31018), 5, SCALAR(0x8a4a8c0), SCALAR(0x8a31018), 5 SCALAR(0x85d3aac), SCALAR(0x85d3aa0), SCALAR(0x85d3a10), SCALAR(0x8a31018), 5
11
13.4 Anonymous Structures Anonymous Structures
Not associated with variable names Only way to access data is through a reference No variable for that data Anonymous array composer Enclose list in square brackets ([) Anonymous hash composer Enclose list in curly braces ({)
12
Creates an array using the anonymous array composer
1 #!/usr/bin/perl 2 # Fig. 13.5: fig13_05.pl 3 # Anonymous arrays and hashes 4 5 use warnings; 6 use strict; 7 8 my $array = [ qw( There was an old lady who lived in a shoe... ) ]; " short" => " and stout..." }; 9 my $hash = { "I'm a" => " little tea cup", 11 13 print( %$hash, "\n" ); 12 print( ); 14 15 my $array2; 18 $array2->[ 2 ] = "sat"; 3 , 4 ] = ( "on", "a" ); 20 print( ); 17 $$array2[ 5 ] = "wall..."; = ( "Humpty", "Dumpty" ); Fig13_05.pl Program Output Creates an array using the anonymous array composer Creating a hash table using the anonymous hash composer Prints the entire anonymous array and hash table Creates an anonymous array without the composer Adding elements to an anonymous array There was an old lady who lived in a shoe... I'm a little tea cup short and stout... Humpty Dumpty sat on a wall...
13
An anonymous function is created and assigned to $productRef
1 #!/usr/bin/perl 2 # Figure 13.6: fig13_06.pl 3 # Anonymous functions 4 5 use warnings; 6 use strict; 7 8 my $productRef = sub 9 { 10 my $product = 1; 11 12 foreach ) { $product *= $_; 14 } 15 16 return $product; 17 }; 18 19 my $printVal = &$productRef( 1, 2, 3, 4 ); 20 print( join( ' * ', 1, 2, 3, 4 ), " = " ); 21 print( "$printVal\n" ); 22 24 print( join( ' * ', 6, 8, -5, 2 ), " = " ); 25 print( "$printVal\n" ); 26 27 $printVal = $productRef->( 4, 3, 2, 1 ); 28 print( join(' * ', 4, 3, 2, 1 ), " = " ); 29 print( "$printVal\n" ); 23 $printVal = $productRef->( 6, 8, -5, 2 ); Fig13_06.pl An anonymous function is created and assigned to $productRef Dereferencing and calling the function Dereferencing and calling the function using the arrow operator
14
Fig13_06.pl Program Output 1 * 2 * 3 * 4 = 24 6 * 8 * -5 * 2 = -480
4 * 3 * 2 * 1 = 24 Fig13_06.pl Program Output
15
Outputting just the name of a function into double quotes (“)
1 #!/usr/bin/perl 2 # Fig. 13.7: fig13_07.pl 3 # Interpolating function returns into a double quoted string. 4 5 use warnings; 6 use strict; 7 8 print( "The number is square( 5 ).\n" ); 9 print( "The number is ${ \square( 5 ) }.\n" ); 10 11 sub square 12 { 13 my $x = shift(); 14 return $x * $x; 15 } Fig13_07.pl Program Output Outputting just the name of a function into double quotes (“) The $ dereferences the reference created, resulting in the return value of the call to square The slash makes a reference to the return value of the call to square The number is square( 5 ). The number is 25.
16
13.5 Closures Anonymous Functions Created during runtime
Execute base on context in which created Act as closures to lexical variables Functions returning anonymous function references
17
$x stored the value passed to the function
1 #!/usr/bin/perl 2 # Fig. 13.8: fig13_08.pl 3 # A simple closure example 4 5 use warnings; 6 use strict; 7 8 sub animalInFood 9 { 10 my $x = shift(); 11 return sub 12 { my $y = shift(); 15 }; 16 } 17 18 my $flyInFood = animalInFood( "fly" ); 19 my $frogInFood = animalInFood( "frog" ); 20 21 &$flyInFood( "soup" ); 22 &$frogInFood( "coffee" ); print( "There is a $x in my $y!\n" ); Fig13_08.pl Program Output $x stored the value passed to the function Uses the value of $x that was created when the function was called Each time the function is called it creates an anonymous function where $x equals the value passed to animalInFood Call anonymous functions that were created There is a fly in my soup! There is a frog in my coffee!
18
13.6 References as Function Arguments
Passing references All passed variables are “flattened” into array Allows anything that can be referenced to be passed Function ref Used to determine the type of reference Returns a string with the reference type
19
This time the function is passed anonymous arrays
1 #!/usr/bin/perl 2 # Fig. 13.9: fig13_09.pl 3 # Demonstrates passing arrays to a function 4 5 use warnings; 6 use strict; 7 8 = ( ); 9 = ( 'a' .. 'e' ); 11 print( ); 12 = arrayMixer( [ 'I', 'to', 'park' ], [ 'go', 'the' ] ); 13 print( ); 14 15 sub arrayMixer 16 { 17 $_[ 0 ] }; 18 $_[ 1 ] }; 19 my ( $first, ); 20 ( $second = shift ) ) ) { 23 $first, $second ); 24 } 25 26 ) if ( $first ); ) if ( $second ); 28 29 30 } 21 while ( ( $first = ) ) && 10 = arrayMixer( ); Fig13_09.pl This time the function is passed anonymous arrays Passes a reference to each array Takes the elements out of each array and stores them into one new array
20
1 a 2 b 3 c 4 d 5 e 6 7 8 I go to the park Fig13_09.pl Program Output
21
Will not return anything because the value is undefined
1 #!/usr/bin/perl 2 # Fig : fig13_10.pl 3 # Demonstrates the return values of the ref function 4 5 use strict; 6 7 = qw( hello world ); 8 my %hash = ( key => "data" ); 9 12 print( = ', ref( ), "\n" ); 11 print( 'ref(\10) = ', ref( \10 ), "\n" ); 13 print( 'ref(\%hash) = ', ref( \%hash ), "\n" ); 14 print( 'ref(\&function) = ', ref( \&function ), "\n" ); 15 print( = ', ref( ), "\n" ); 16 print( 'ref(\*hash) = ', ref( \*hash ), "\n" ); 17 18 sub function 19 { 20 print( "Hello world.\n" ); 21 } 10 print( 'ref(10) = ', ref( 10 ), "\n" ); # undefined Fig13_10.pl Program Output Will not return anything because the value is undefined Each will return a string containing type referenced ref(10) = ref(\10) = SCALAR = ARRAY ref(\%hash) = HASH ref(\&function) = CODE = REF ref(\*hash) = GLOB
22
Calls printStructures sending it the four items just created
1 #!/usr/bin/perl 2 # Fig : fig13_11.pl 3 # Using ref inside a function 4 5 use strict; 6 use warnings; 7 8 = ( "This","is","the","first","array." ); 9 = ( "This","is","the","second","array." ); 10 my %hash = ( Tarzan => "Jane", Superman => "Lois Lane", Batman => "Catwoman", ); 13 my $array3 = [ "anonymous", [ "array", "in", "an", "array" ], { "plus" => "a", "hash" => "in", }, "as", "well" ]; 18 19 printStructures( 5, \%hash, $array3); 20 Fig13_11.pl Calls printStructures sending it the four items just created
23
If the reference is a scalar then it is printed out
21 sub printStructures 22 { 23 my $indent = shift(); 24 25 foreach my $element ) { 26 unless ( ref( $element ) ) { print( ' ' x $indent, $element, "\n" ); } elsif ( ref( $element ) eq 'SCALAR' ) { } print( ' ' x $indent, $element, "\n" ); 34 elsif ( ref( $element ) eq 'ARRAY' ) { foreach ( 0 .. $#$element ) { print( ' ' x $indent, "[ $_ ] " ); 37 if ( ref( $element->[ $_ ] ) ) { print( "\n" ); } printStructures( $indent + 3, $element->[ $_ ]); else { print( "$element->[ $_ ]\n" ); } } } Fig13_11.pl If the reference is a scalar then it is printed out If the reference is an array print out each of its elements If the element contains more references then use recursion
24
If the reference is a hash then elements and keys are printed
elsif ( ref( $element ) eq 'HASH' ) { 48 foreach my $key ( keys( %$element ) ) { print( ' ' x $indent, $key, ' => ' ); 51 if ( ref ( $element->{ $key } ) ) { print( "\n" ); printStructures( $indent + 3, $element->{$key} ); } else { print( "$element->{ $key }\n" ); } } } elsif ( ref( $element ) eq 'CODE' ) { print( ' ' x $indent, "CODE\n" ); } elsif ( ref( $element ) eq 'GLOB' ) { print( ' ' x $indent, "GLOB\n" ); } 67 print( "\n" ); 69 } 70 } If the reference is a hash then elements and keys are printed Fig13_11.pl If it is a function If it is a typeglob
25
Fig13_11.pl Program Output [ 0 ] This [ 1 ] is [ 2 ] the [ 3 ] first
[ 4 ] array. Batman => Catwoman Superman => Lois Lane Tarzan => Jane [ 3 ] second [ 0 ] anonymous [ 1 ] [ 0 ] array [ 1 ] in [ 2 ] an [ 3 ] array [ 2 ] hash => in plus => a [ 3 ] as [ 4 ] well Fig13_11.pl Program Output
26
13.7 Nested Data Structures
Array of arrays Two-dimensional array An array whose elements are each references to other arrays Needs two subscripts in order to access the correct value First for original array Second for the proper location in the nested array $array[ $i ] -> [ $j ] (arrow notation) $array[ $i ] [ $j ] (better notation) Does not have to be arrays Hashes of hashes Hashes of arrays Arrays of hashes Multi-dimensional as well
27
The creating of a two-dimensional array using a foreach loop
1 #!/usr/bin/perl 2 # Fig : fig13_12.pl 3 # Shows how to use two dimensional arrays. 4 5 use warnings; 6 use strict; 7 8 9 10 foreach my $outer ( ) { 11 12 foreach my $inner ( ) { $array[ $outer ][ $inner ] = $outer * $inner; 14 } 15 } 16 17 foreach ( 0 .. $#array ) { 18 $array[ $_ ]->[ 4 ] = $_ * 4; 19 } 20 21 print( ); 22 [ 0, 4, 8, 12, 16 ] ); 23 24 print( "\$array[ 1 ]->[ 3 ] = $array[ 1 ]->[ 3 ]\n" ); 25 print( "\$array[ 2 ][ 3 ] = $array[ 2 ][ 3 ]\n" ); 26 print( 1 ] 1 ]}\n\n" ); 27 Fig13_12.pl The creating of a two-dimensional array using a foreach loop Will output address values
28
Manually creating a two-dimensional array of anonymous arrays
28 = ( 29 [ 1, 2, 3, 4 ], 30 [ 2, 3, 4, 5 ], 31 [ 3, 4, 5, 6 ], 32 [ 4, 5, 6, 7 ] 33 ); 34 35 my $array3 = [ 36 [ 1, 2, 3, 4 ], 37 [ 2, 3, 4, 5 ], 38 [ 3, 4, 5, 6 ], 39 [ 4, 5, 6, 7 ] 40 ]; 41 42 foreach ( 0 .. $#array ) { 43 print( $array[ $_ ] }\n" ); 44 } 45 46 print( "\n" ); 47 48 foreach my $row ) { 49 print( ); 50 } 51 52 print( "\n$array3->[ 2 ][ 2 ]\n" ); Manually creating a two-dimensional array of anonymous arrays Fig13_12.pl Creates a reference to an array of arrays Go through each element of the array and print it out Store each element into $row and then dereference and displays it
29
ARRAY(0x85d3ad0) ARRAY(0x85deb24) ARRAY(0x85debb4) ARRAY(0x85dec44)
5 Fig13_12.pl Program Output
30
Call a function based on user input
1 #!/usr/bin/perl 2 # Fig : fig13_13.pl 3 # Demonstrates a hash of arrays 4 5 use warnings; 6 use strict; 7 8 instructions(); 9 my $choice = prompt(); 10 my %hash; 11 13 addElement() if ( $choice eq 'a' ); 12 while ( $choice ne 'q' ) { 14 deleteElement() if ( $choice eq 'd' ); 15 deleteKey() if ( $choice eq 'k' ); 16 printAll() if ( $choice eq 'p' ); 17 instructions() if ( $choice eq 'i' ); 18 $choice = prompt(); 19 } 20 21 sub instructions 22 { 24 Enter 'a' to add an element. 23 print <<DONE; 25 Enter 'd' to delete an element. 26 Enter 'k' to delete a key. 27 Enter 'p' to print all elements. 28 Enter 'q' to quit. 29 DONE 30 } 31 Fig13_13.pl Call a function based on user input Shows the choices the user can choose
31
Adds an element to the hash table, and key if needed
32 sub prompt 33 { 34 print( "? " ); 35 chomp( my $answer = <STDIN> ); 36 return $answer; 37 } 38 40 { 39 sub addElement 41 print( "What is the key you would like to add? " ); 42 chomp( my $key = <STDIN> ); 43 print( "What is the value? " ); 44 chomp( my $value = <STDIN> ); 45 $hash{ $key } }, $value; 46 } 47 49 { 48 sub deleteElement 50 print( "What is the key of the element? " ); 51 chomp( my $key = <STDIN> ); 52 print( "What is the value of the element? " ); 53 chomp( my $value = <STDIN> ); 54 55 for ( 0 .. $#{ $hash{ $key } } ) { 56 if ( $hash{ $key }[ $_ ] eq $value ) { print( "Deleting element $hash{ $key }[ $_ ]\n" ); 59 $hash{ $key } }, $_, 1 ); return; } 62 } 63 } Fig13_13.pl Adds an element to the hash table, and key if needed Remove an element from the table
32
Remove a key from the table Fig13_13.pl
64 65 sub deleteKey 66 { 67 print( "What key would you like to delete? " ); 68 chomp( my $key = <STDIN> ); 69 delete( $hash{ $key } ); 70 } 71 72 sub printAll 73 { 74 foreach ( keys( %hash ) ) { print( " $_ => ", join( ', $hash{ $_ } } ), "\n" ); 76 } 77 } Remove a key from the table Fig13_13.pl
33
Fig13_13.pl Program Output Enter 'a' to add an element.
Enter 'd' to delete an element. Enter 'k' to delete a key. Enter 'p' to print all elements. Enter 'q' to quit. ? a What is the key you would like to add? duck What is the value? Huey What is the value? Louie ?a What is the value? Dewey What is the key you would like to add? horse What is the value? Mr. Ed What is the key you would like to add? dog What is the value? Lassie What is the value? Benji ? p dog => Lassie, Benji duck => Huey, Louie, Dewey horse => Mr. Ed Fig13_13.pl Program Output
34
Fig13_13.pl Program Output ? d What is the key of the element? duck
What is the value of the element? Huey Deleting element Huey ? k What key would you like to delete? dog ? p duck => Louie, Dewey horse => Mr. Ed ? q Fig13_13.pl Program Output
35
13.8 Garbage Collection and Circular References
Memory Management Memory is automatically freed in Perl Garbage Collector Frees memory that has no references to it Reference count When 0 memory is reclaimed Circular References Reference count never gets to 0 Memory leak
36
Using Symbolic References
Refer to another variable by holding the variable’s name Used when don’t know variable name until runtime Can overwrite variable Using Symbolic References Creating Set variable equal to the name of the variable to be referenced Disabling error Generated from sing reference variables no strict ‘refs’
37
Gets the variable to be modified from the user
1 #!/usr/bin/perl 2 # Fig : fig13_14.pl 3 # Demonstrates symbolic references 4 5 use warnings; 6 use strict; 7 no strict 'refs'; 8 9 my ( ); 10 instructions(); 11 12 do { 13 print( "? " ); 14 chomp( $choice = <STDIN> ); 15 16 if ( $choice eq 'v' ) { print( "What variable would you like to add to? " ); chomp( my $name = <STDIN> ); 19 if ( !( $$name ) ) { 21 $name ); $$name = 0; } 24 $$name += 20; 26 } 27 Used to eliminate the error that Perl generates for using symbolic references. Fig13_14.pl Gets the variable to be modified from the user Stores the variables in an array and sets their initial value to zero
38
Prints the desired variable with the appropriate value Fig13_14.pl
28 if ( $choice eq 'p' ) { print( "What variable would you like to print? " ); chomp( my $name = <STDIN> ); print( "$$name\n" ); 32 } 33 34 if ( $choice eq 'a' ) { 35 foreach my $name ) { print( "\$$name = $$name\n" ); } 39 } 40 41 instructions() if ( $choice eq 'i' ); 42 43 } while ( $choice ne 'q' ); 44 45 sub instructions 46 { 47 print <<DONE; 48 Enter 'v' to add to a variable 49 Enter 'p' to print a variable 50 Enter 'a' to print all the variables 51 Enter 'i' to print the instructions 52 Enter 'q' to quit 53 DONE 54 } Prints the desired variable with the appropriate value Fig13_14.pl Displays all the variable names and their values Displays the instructions again for the user
39
Fig13_14.pl Program Output Enter 'v' to add to a variable
Enter 'p' to print a variable Enter 'a' to print all the variables Enter 'i' to print the instructions Enter 'q' to quit ? v What variable would you like to add to? name1 What variable would you like to add to? name2 What variable would you like to add to? name3 ? p What variable would you like to print? name1 60 ? a $name1 = 80 $name2 = 40 $name3 = 20 ? q Fig13_14.pl Program Output
40
13.10 Typeglobs References Typeglob Fairly new to Perl
Previously used a typeglob Typeglob Each has entry in symbolic table Perl’s symbolic table Contains different variable types for each name *variableName Typeglobs can be assigned to each other Variables act as synonyms to one another Cannot use my variables Creates constants
41
A scalar assigned to *cow
1 #!/usr/bin/perl 2 # Fig : fig13_15.pl 3 # Demonstrates the use of typeglobs 4 5 use warnings; 6 use strict; 8 12 14 { 15 print <<'DONE'; 16 \__/ 19 / || 21 /|| /||| | | 23 DONE 24 } 25 27 28 print( "Printing Cow.\n" ); 29 printAnimal( *cow ); 30 _____________/oo\ 22 |_| |_| 20 /| _______ / 7 no strict 'vars'; 13 sub cow = ( 'gills', 'brain', 'eyes', '', 'feet', '', 'udders' ); 10 %cow = ( sound => "mooo" ); 9 $cow = "cow"; 26 *heifer = *cow; Fig13_15.pl Needed to make variable assignment be inserted into the table, no my variable A scalar assigned to *cow A hash assigned to *cow An array assigned to *cow A function assigned to *cow Setting all the variables with cow in them to be the same a heifer
42
Change values of heifer typeglob Fig13_15.pl
31 $heifer[ 2 ] = 'nostrils'; 32 $heifer[ 4 ] = 'stomachs'; 33 34 print( "\nPrinting modified cow.\n" ); 35 printAnimal( *cow ); 36 37 print( "\nChanging the cow's name\n" ); 38 39 { 40 my $newname = "heifer"; 41 *heifer = \$newname; 42 } 43 44 printAnimal( *heifer ); 45 46 sub printAnimal 47 { 48 local *animal = shift(); 49 print( "A $animal goes $animal{ sound }!\n" ); 50 51 for ( my $i = $#animal; $i >= 0; $i-- ) { print( "A $animal has $i $animal[ $i ]!\n" ) if ( $animal[ $i ] ); 54 } 55 56 print( "A $animal looks something like this.\n" ); 57 animal(); 58 } Change values of heifer typeglob Fig13_15.pl Changes the scalar variable in heifer, will also effect cow The function that takes a typeglob as an argument an uses all of its parts
43
Fig13_15.pl Program Output Printing Cow. A cow goes mooo!
A cow has 6 udders! A cow has 4 feet! A cow has 2 eyes! A cow has 1 brain! A cow has 0 gills! A cow looks something like this. \__/ _____________/oo\ / || /| _______ / /|| /||| | | |_| |_| Printing modified cow. A cow has 4 stomachs! A cow has 2 nostrils! Fig13_15.pl Program Output
44
Fig13_15.pl Program Output Changing the cow's name A heifer goes mooo!
A heifer has 6 udders! A heifer has 4 stomachs! A heifer has 2 nostrils! A heifer has 1 brain! A heifer has 0 gills! A heifer looks something like this. \__/ _____________/oo\ / || /| _______ / /|| /||| | | |_| |_| Fig13_15.pl Program Output
45
Setting a reference to a typeglob
1 #!/usr/bin/perl 2 # Fig : fig13_16.pl 3 # Two more ways of using typeglobs 4 5 use warnings; 6 use strict; 7 no strict 'vars'; 8 9 $variable = 10; = ( 1, 2, 3, 4, 5 ); 11 12 sub variable 13 { 14 print( "green\n" ); 15 } 16 17 print( "$variable\n" ); 18 print( ); 19 variable(); 20 22 $arrayRef = *variable{ ARRAY }; 21 $scalarRef = *variable{ SCALAR }; 23 $codeRef = *variable{ CODE }; 24 26 print( ); 27 &$codeRef(); 28 29 print( "${ *variable }\n" ); 30 print( *variable }\n" ); 31 &{ *variable }; 25 print( "$$scalarRef\n" ); Fig13_16.pl Setting a reference to a typeglob Typeglobs can be dereferenced just as other variable can
46
10 green Fig13_16.pl Program Output
47
13.11 Referencing Filehandles
Have no special character identification Cannot be referenced Typeglobs allow filehandles to be referenced Can then be stored into a scalar and used where appropriate
48
Assigns the $filehandle of typeglob for TEXT
1 #!/usr/bin/perl 2 # Fig : fig13_17.pl 3 # Demonstrates using typeglobs to alias filehandles 4 5 use warnings; 6 use strict; 7 8 open( TEXT, 'fig13_17.pl' ) or die( "File could not be opened : $!" ); 10 12 my $out = *STDOUT; 13 14 while ( <$filehandle> ) { 16 } 15 printf( $out "%-3d %s", $., $_ ); 11 my $filehandle = *TEXT; Fig13_17.pl Program Output Assigns the $filehandle of typeglob for TEXT Writes to $out using printf 1 #!/usr/bin/perl 2 # Figure 13.17: fig13_17.pl 3 # Demonstrates using typeglobs to alias filehandles 4 5 use warnings; 6 use strict; 7 8 open( TEXT, 'fig13_17.pl' ) or die( "File could not be opened : $!" ); 10 11 my $filehandle = *TEXT; 12 my $out = *STDOUT; 13 14 while ( <$filehandle> ) { printf( $out "%-3d %s", $., $_ ); 16 }
49
Passes a typeglob to a function
1 #!/usr/bin/perl 2 # Fig : fig13_18.pl 3 # Passing filehandles to functions 4 5 use warnings; 6 use strict; 7 8 my $file = ); 9 open( FILE, $file ) or die( "Error opening $file: $!" ); 10 my $filehandle = *FILE; 11 readhandle( $filehandle ); 12 close( FILE ) or die( "Error closing $file: $!" ); 13 14 print( "\n\nNow a 2nd time...\n" ); 15 open( FILE, $file ) or die( "Error opening $file: $!" ); 16 $filehandle = \*FILE; 17 readhandle( $filehandle ); 18 close( FILE ) or die( "Error closing $file: $!" ); 19 20 print( "\n\nAnd finally...\n" ); 21 readfile( $file ); 22 23 sub readhandle 24 { 25 my $fh = shift(); 26 print while ( <$fh> ); 27 } 28 Fig13_18.pl Passes a typeglob to a function Passes the reference of a typeglob to a function Passes the file itself to be opened in the function
50
Will open the file before it tries to use it Fig13_18.pl
29 sub readfile 30 { 31 my $file = shift(); 32 local *FILE; 33 open( FILE, $file ) or die( "Error opening $file: $!" ); 34 print while ( <FILE> ); 35 } Will open the file before it tries to use it Fig13_18.pl Program Output This is a sample text file... Now a 2nd time... And finally... This is a sample text file..
51
13.11 Referencing Filehandles
This is a sample text file... Fig Contents of sample.txt file used for $file.
52
13.12 Uses for References Modules
Pass option lists or preference lists to a function CGI.pm Used to provide syntax to indicate HTML tag attributes
53
When calling the p function it generates the <P> tag
1 #!/usr/bin/perl 2 # Fig : fig13_20.pl 3 # Demonstrates the reference syntax 4 5 use warnings; 6 use strict; 7 use CGI::Pretty qw( :standard ); 8 9 print( header(), start_html( 'Demo' ), p( 'Some', 'random', 'text' ), p( { -align => 'right' }, 'right', 'aligned text' ), p( { -align => 'center' }, [ 'on', 'separate', 'lines' ] ), end_html() ); Fig13_20.pl When calling the p function it generates the <P> tag Hashes can be used with align references to align text in HTML Center alignment is repeated for each item in the array
54
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<HTML><HEAD><TITLE>Demo</TITLE> </HEAD><BODY> <P> Some random text </P> <P ALIGN="right"> right aligned text <P ALIGN="center"> on separate lines </BODY></HTML> Fig13_20.pl Program Output
55
Uses a hash reference to assign attributes to an image
1 #!/usr/bin/perl 2 # Fig : fig13_21.pl 3 # Use of references in CGI.pm 4 5 use strict; 6 use warnings; 7 use CGI::Pretty qw( :standard :html3 ); 8 9 = qw( and a few ); 10 print header(), start_html( 'Hash and array references with CGI.pm' ), h1( "Here's a list!!!!" ), ol( ul( li( ) ), 'more' ] ) ), h2( "Now were going to have a table." ), caption( strong( "Hi, I'm a table" ) ), Tr( { -align => 'CENTER' }, [ th( [ '', 'Col1', 'Col2', 'Col3' ] ), th( 'Row1' ).td( [ 'val1', 'val2', 'val3' ] ), th( 'Row2' ).td( [ 'val4', 'val5', 'val6' ] ), th( 'Row3' ).td( [ 'val7', 'val8', 'val9' ] ) ] ) ), img( { -src => '/images/image.gif', -alt => 'Image' } ), li( [ 'a', 'bunch', 'of', 'elements'. table( { border => 2 }, Fig13_21.pl Uses a hash reference to assign attributes to an image Creates individual li tags because an array is used Creates a table using a combination of array and hash references
56
Fig13_21.pl Creates 3 hidden tags Creates a popup menu
start_form( -action => '/cgi-bin/ch13/fig13_21.pl' ), hidden( -name => 'name', value => [ 'val1', 'val2', 'val3' ] ), popup_menu( -name => 'menu', value => [ 'c1', 'c2', 'c3', 'c4' ], default => 'c2' ), radio_group( -name => 'choices', value => [ 'c1', 'c2', 'c3', 'c4' ], default => 'c2' ), end_form(), end_html(); Creates 3 hidden tags Fig13_21.pl Creates a popup menu Creates a radio group
57
Fig13_21.pl Program Output
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.