1 / 32

Subroutines and Functions

Subroutines and Functions. boss. worker1. worker2. worker3. worker4. worker5. Fig. 6.1 Hierarchical boss–subroutine/worker–subroutine relationship. 1 #!/usr/bin/perl. 2 # Fig. 6.3: fig06_03.pl. 3 # Demonstrating some math functions. 4 .

lintonm
Download Presentation

Subroutines and Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Subroutines and Functions

  2. boss worker1 worker2 worker3 worker4 worker5 Fig. 6.1 Hierarchical boss–subroutine/worker–subroutine relationship.

  3. 1 #!/usr/bin/perl 2 # Fig. 6.3: fig06_03.pl 3 # Demonstrating some math functions. 4 The expression abs($x) returns the absolute value of x. 5 $_ = -2; 6 print "Absolute value of 5 is: ", abs( 5 ), "\n", The expression exp($x) returns e to the power of x. 7 "Absolute value of -5 is: ", abs( -5 ), "\n", 8 "Absolute value of $_: ", abs, "\n\n"; The expression log($x) returns the natural logarithm of x. The expression sqrt($x) returns the square root of x. 9 10 print "exp( $_ ): ", exp, "\n"; 11 print "log( 5 ): ", log( 5 ), "\n"; 12 print "sqrt( 16 ): ", sqrt( 16 ), "\n"; Absolute value of 5 is: 5 Absolute value of -5 is: 5 Absolute value of -2: 2 exp( -2 ): 0.135335283236613 log( 5 ): 1.6094379124341 sqrt( 16 ): 4

  4. 1 #!/usr/bin/perl 2 # Fig 6.4: fig06_04.pl 3 # User-defined subroutines that take no arguments. 4 5 subroutine1(); # call the subroutine with no arguments This line calls (or invokes) subroutine1. Normally, subroutines are called by following the subroutine name with a set of parentheses. An empty set of parentheses indicates that the subroutine does not receive any arguments. This line calls (or invokes) subroutine2. 6 subroutine2(); # call the subroutine with no arguments When it is called, the body of the subroutine executes to perform the subroutine’s task (display the string "called subroutine1\n"). 7 8 # the code after this comment executes only if the program When it is called, the body of the subroutine executes to perform the subroutine’s task (display the string "called subroutine2\n"). 9 # explicitly calls these subroutines (as in lines 5 and 6). 10 sub subroutine1 11 { 12 print "called subroutine1\n"; 13 } 14 15 sub subroutine2 16 { 17 print "called subroutine2\n"; 18 } called subroutine1 called subroutine2

  5. 1 #!/usr/bin/perl 2 # Fig 6.5: fig06_05.pl 3 # Demonstrating a subroutine that receives arguments. 4 This line calls subroutine displayArguments with six string and numeric arguments. 5 displayArguments( "Sam", "Jones", 2, 15, 73, 2.79 ); 6 Displays the contents of the entire arguments array with each argument separated by a space. 7 # output the subroutine arguments using special variable @_ 8 sub displayArguments The list of arguments passed to a function is stored in the special array variable @_. The for structure accesses each argument individually, with the expression $_[$i], and displays the argument value. 9 { 10 # the following statement displays all the arguments 11 print "All arguments: @_\n"; 12 13 # the following loop displays each individual argument 14 for ( $i = 0; $i < @_; ++$i ) { 15 print "Argument $i: $_[ $i ]\n"; 16 } 17 } All arguments: Sam Jones 2 15 73 2.79 Argument 0: Sam Argument 1: Jones Argument 2: 2 Argument 3: 15 Argument 4: 73 Argument 5: 2.79

  6. 1 #!/usr/bin/perl 2 # Fig 6.6: fig06_06.pl 3 # Demonstrating a subroutine that returns a value. The for structure calls subroutine square repeatedly with each of the values from 1 through 10. In each call , the value of $_ passed as an argument to square is stored in the special array for arguments, @_. 4 Subroutine square, which calculates the square of the value the subroutine receives as its argument. Function shift, when used without any arguments, operates on the @_ special array variable and removes the first element of the array. Displays the squared value followed by a space. 5 # for the numbers from 1-10, call subroutine square to 6 # square each value, and display each result 7 for ( 1 .. 10 ) { 8 print square( $_ ), " "; Evaluates the expression $value**2 (the square of $value) and passes the result back to the caller via the return keyword. 9 } 10 11 print "\n"; 12 13 # subroutine square returns the square of a number 14 sub square 15 { 16 $value = shift(); # use shift to get first argument 17 return $value ** 2; # returns the result of $value ** 2 18 } 1 4 9 16 25 36 49 64 81 100

  7. 1 #!/usr/bin/perl 2 # Fig 6.7: fig06_07.pl 3 # Demonstrating a subroutine that returns a scalar or a list. Uses the return value of scalarOrList to initialize @array. This is a list context. 4 5 # call scalarOrList() in list context to initialize @array, 6 # then print the list The value in $" specifies what will be printed in between the values of an array when an array is printed in double quotes. As a result, when @array is printed, each element is printed on a separate line. 7 @array = scalarOrList(); # list context to initialize @array When called in the body of a subroutine, function wantarray returns true if the subroutine was called from a list context and returns false if the subroutine was called from a scalar context. 8 $" = "\n"; # set default separator character 9 print "Returned:\n@array\n"; Uses the return value of scalarOrList in a string-concatenation operation. This is a scalar context. 10 11 # call scalarOrList() in scalar context and concatenate the 12 # result to another string 13 print "\nReturned: " . scalarOrList(); # scalar context 14 15 # use wantarray to return a list or scalar 16 # based on the calling context 17 sub scalarOrList 18 { 19 if ( wantarray() ) { # if list context 20 return 'this', 'is', 'a', 'list', 'of', 'strings'; 21 } 22 else { # if scalar context 23 return 'hello'; 24 } 25 }

  8. Returned: this is a list of strings Returned: hello

  9. 1 #!usr/bin/perl 2 # Fig 6.8: fig06_08.pl 3 # Syntax for calling a subroutine. 4 5 # subroutine with no arguments defined before it is used 6 sub definedBeforeWithoutArguments 7 { 8 print "definedBeforeWithoutArguments\n"; Call subroutines with both & and (). 9 } 10 Call subroutines with the common () notation. 11 # subroutine with arguments defined before it is used 12 sub definedBeforeWithArguments 13 { 14 print "definedBeforeWithArguments: @_\n"; 15 } 16 17 # calling subroutines that are defined before use 18 print "------------------------------\n"; 19 print "Subroutines defined before use\n"; 20 print "------------------------------\n"; 21 print "Using & and ():\n"; 22 &definedBeforeWithoutArguments(); 23 &definedBeforeWithArguments( 1, 2, 3 ); 24 25 print "\nUsing only ():\n"; 26 definedBeforeWithoutArguments(); 27 definedBeforeWithArguments( 1, 2, 3 ); 28

  10. 29 print "\nUsing only &:\n"; 30 &definedBeforeWithoutArguments; definedBeforeWithoutArguments is called with an & but no parentheses. This syntax is not allowed for subroutines that are passed explicit arguments. Call the subroutines again as barewords without & or parentheses. This syntax works only because the subroutines are defined before they are called. 31 print "\"&definedBeforeWithArguments 1, 2, 3\"", 32 " generates a syntax error\n"; 33 34 print "\nUsing bareword:\n"; Subroutines that are defined after they are used in the program are invoked correctly when using & and () or when using just (). 35 definedBeforeWithoutArguments; 36 definedBeforeWithArguments 1, 2, 3; The subroutine without arguments did not cause an action to occur, because there was no context to help Perl determine the purpose of the identifier. Subroutines with arguments can be called with the & syntax only if parentheses are used also. 37 The subroutine with arguments is not called, because it would cause a syntax error. 38 # calling subroutines that are not defined before use 39 print "\n-----------------------------\n"; 40 print "Subroutines defined after use\n"; 41 print "-----------------------------\n"; 42 print "Using & and ():\n"; 43 &definedAfterWithoutArguments(); 44 &definedAfterWithArguments( 1, 2, 3 ); 45 46 print "\nUsing only ():\n"; 47 definedAfterWithoutArguments(); 48 definedAfterWithArguments( 1, 2, 3 ); 49 50 print "\nUsing only &:\n"; 51 &definedAfterWithoutArguments; 52 print "\"&definedAfterWithArguments 1, 2, 3\"", 53 " generates a syntax error\n"; 54 55 print "\nUsing bareword:\n"; 56 definedAfterWithoutArguments; 57 print "\"definedAfterWithoutArguments\" causes no action\n"; 58 print "\"definedAfterWithArguments 1, 2, 3\"", 59 " generates a syntax error\n"; 60

  11. 61 # subroutine with no arguments defined after it is used 62 sub definedAfterWithoutArguments 63 { 64 print "definedAfterWithoutArguments\n"; 65 } 66 67 # subroutine with arguments defined after it is used 68 sub definedAfterWithArguments 69 { 70 print "definedAfterWithArguments: @_\n"; 71 } ------------------------------ Subroutines defined before use ------------------------------ Using & and (): definedBeforeWithoutArguments definedBeforeWithArguments: 1 2 3 Using only (): definedBeforeWithoutArguments definedBeforeWithArguments: 1 2 3 Using only &: definedBeforeWithoutArguments "&definedBeforeWithArguments 1, 2, 3" generates a syntax error Using bareword: definedBeforeWithoutArguments definedBeforeWithArguments: 1 2 3

  12. ----------------------------- Subroutines defined after use ----------------------------- Using & and (): definedAfterWithoutArguments definedAfterWithArguments: 1 2 3 Using only (): definedAfterWithoutArguments definedAfterWithArguments: 1 2 3 Using only &: definedAfterWithoutArguments "&definedAfterWithArguments 1, 2, 3" generates a syntax error Using bareword: "definedAfterWithoutArguments" causes no action "definedAfterWithArguments 1, 2, 3" generates a syntax error

  13. 1 #!usr/bin/perl 2 # Fig. 6.9: fig06_09.pl 3 # Demonstrating function rand. The function rand generates a floating-point scalar value greater than or equal to 0 and less than 1. 4 5 print "Random numbers produced by rand():\n"; The call to rand in this expression produces a value greater than or equal to 0 and less than 6. That value is truncated with int to produce integers in the range from 0 through 5. We then add 1 to the result to produce a value in the range from 1 through 6, which could be used to simulate the rolling of a six-sided die in a game. 6 7 for ( 1 .. 3 ) { 8 print " ", rand(), "\n"; 9 } We can manually set the range of values that rand returns by passing it a numeric argument. In this case, rand returns a random value greater than or equal to 0 and less than the argument. 10 11 print "\nRandom numbers produced by rand( 100 ):\n"; 12 13 for ( 1 .. 3 ) { 14 print " ", rand( 100 ), "\n"; 15 } 16 17 print "\nRandom integers produced by 1 + int( rand( 6 ) ):\n"; 18 19 for ( 1 .. 3 ) { 20 print " ", 1 + int( rand( 6 ) ), "\n"; 21 }

  14. Random numbers produced by rand(): 0.76605224609375 0.387115478515625 0.648834228515625 Random numbers produced by rand( 100 ): 32.4371337890625 90.948486328125 83.7890625 Random integers produced by 1 + int( rand( 6 ) ): 6 4 1

  15. 1 #!/usr/bin/perl 2 # Fig. 6.10: fig06_10.pl 3 # Seeding the random number generator. The random numbers produced by rand are based on an algorithm that uses the previous random number and a seed to create the next random number. Function srand sets the seed during each iteration of the for structure. 4 5 # during each iteration, set seed to 1, 6 # then produce three random integers The sequence of pseudorandom numbers repeats itself each time the seed is set to the same value. 7 for ( 1 .. 3 ) { This causes the computer to read its system clock to obtain the value for the seed automatically. This is the default behavior for srand. 8 print "\n\nSetting seed to 1\n"; 9 srand( 1 ); 10 By allowing the system to determine the seed, different sets of random values are generated each time. 11 # produces same three values each time 12 for ( 1 .. 3 ) { 13 print " ", 1 + int( rand( 6 ) ); 14 } 15 } 16 17 print "\n\nResetting seed\n"; 18 srand(); # let system determine seed 19 20 for ( 1 .. 3 ) { 21 22 print "\n\nAfter seed has been reset\n"; 23 24 for ( 1 .. 3 ) { 25 print " ", 1 + int( rand( 6 ) ); 26 } 27 28 } 29 30 print "\n";

  16. Setting seed to 1 1 4 2 Setting seed to 1 1 4 2 Setting seed to 1 1 4 2 Resetting seed After the seed has been reset 2 4 6 After the seed has been reset 5 5 2 After the seed has been reset 4 5 5

  17. 1 #!/usr/bin/perl The game begins by calling subroutine rollDice to roll the dice, compute and print their sum and return the sum. 2 # Fig. 6.11: fig06_11.pl 3 # The game of Craps. If the game is over after the first roll (i.e., the sum of the dice is 7, 11, 2, 3 or 12), variable $status is set to "WON" or "LOST". The if/elsif/else structure determines the status of the game after the first roll. 4 5 $roll = rollDice(); # start the game If the game is not over after the first roll, $roll (i.e., the sum of the two dice) is saved in $myPoint. Execution proceeds with the while structure because $status is equal to "CONTINUE". 6 7 # determine if the game is a win or loss, Each iteration of the while loop calls rollDice to produce a new $roll. 8 # or if the game should continue 9 if ( $roll == 7 or $roll == 11 ) { # won? If $roll matches $myPoint, $status is set to "WON", the while condition fails, the congratulatory message prints and execution terminates. If $roll is equal to 7, $status is set to "LOST", the while condition fails, the message "Sorry, you lost." prints and the program terminates. 10 $status = "WON"; 11 } 12 elsif ( $roll == 2 or $roll == 3 or $roll == 12 ) { # lost? 13 $status = "LOST"; 14 } 15 else { # game continues 16 $status = "CONTINUE"; 17 $myPoint = $roll; # must roll this before 7 to win 18 print "Point is $myPoint.\n"; 19 } 20 21 while ( $status eq "CONTINUE" ) { # game not won or lost 22 $roll = rollDice(); # roll dice again 23 24 if ( $roll == $myPoint ) { # won? 25 $status = "WON"; 26 } 27 elsif ( $roll == 7 ) { # lost? 28 $status = "LOST"; 29 } 30 }

  18. 31 32 print message( $status ); # display message with result 33 Subroutine rollDice rolls the dice, computes and prints their sum and returns the sum. 34 # subroutines to support the game of craps 35 36 # rollDice rolls two dice and returns the sum of the dice 37 sub rollDice Subroutine rollDie is called by rollDice to generate a random number from 1 through 6. 38 { Subroutine message takes a single argument (WON or LOST) and returns an appropriate message indicating whether the game was won or lost. 39 ( $die1, $die2 ) = ( rollDie(), rollDie() ); 40 $sum = $die1 + $die2; 41 print "Player rolled $die1 + $die2 = $sum.\n"; 42 return $sum; 43 } 44 45 # rollDie rolls one die and returns its value 46 sub rollDie 47 { 48 return 1 + int( rand( 6 ) ); 49 } 50 51 # prints a message based 52 sub message 53 { 54 $status = shift; # get argument value 55 return "Sorry, you lost.\n" if $status eq "LOST"; 56 return "Congratulations, you won!\n"; 57 }

  19. Player rolled 6 + 5 = 11. Congratulations, you won! Player rolled 1 + 1 = 2. Sorry, you lost. Player rolled 4 + 6 = 10. Point is 10. Player rolled 2 + 4 = 6. Player rolled 6 + 5 = 11. Player rolled 3 + 3 = 6. Player rolled 6 + 4 = 10. Congratulations, you won! Player rolled 1 + 3 = 4. Point is 4. Player rolled 1 + 4 = 5. Player rolled 5 + 4 = 9. Player rolled 4 + 6 = 10. Player rolled 6 + 3 = 9. Player rolled 1 + 2 = 3. Player rolled 5 + 2 = 7. Sorry, you lost.

  20. Final value = 120 5! 5! 5! = 5 * 24 = 120 is returned 5 * 4! 5 * 4! 4! = 4 * 6 = 24 is returned 4 * 3! 4 * 3! 3! = 3 * 2 = 6 is returned 3 * 2! 3 * 2! 2! = 2 * 1 = 2 is returned 2 * 1! 2 * 1! 1 returned 1 1 a) Procession of recursive calls. b) Values returned from each recursive call. Fig. 6.12 Recursive evaluation of 5!.

  21. 1 #!/usr/bin/perl 2 # Fig. 6.13: fig06_13.pl 3 # Recursive factorial subroutine 4 5 # call function factorial for each of the numbers from The recursive subroutine factorial sets the variable $number to the first argument it receives. It also uses the keyword my to the left of the variable named $number. This keyword creates what is called a lexically scoped variable. The subroutine tests the base case to determine whether a terminating condition is true, i.e., is $number less than or equal to 1. If $number is indeed less than or equal to 1, factorial returns 1, no further recursion is necessary and the subroutine terminates. 6 # 0 through 10 and display the results 7 foreach ( 0 .. 10 ) { 8 print "$_! = " . factorial( $_ ) . "\n"; 9 } If $number is greater than 1, the recursive step expresses the problem as the product of $number (an expression that evaluates to a simple numeric value) and a recursive call to factorial evaluating the factorial of $number-1. 10 11 # factorial recursively calculates the factorial of the 12 # argument it receives 13 sub factorial 14 { 15 my $number = shift; # get the argument 16 17 if ( $number <= 1 ) { # base case 18 return 1; 19 } 20 else { # recursive step 21 return $number * factorial( $number - 1 ); 22 } 23 }

  22. 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800

  23. 1 #!/usr/bin/perl 2 # Fig 6.14: fig06_14.pl 3 # Recursive fibonacci function. 4 5 @sampleValues = (0, 1, 2, 3, 4, 5, 6, 10, 20, 30, 35); 6 7 # Calculate and print the fibonacci value of all the above values Each fibonacci call immediately tests for the base case—$number equal to 0 or 1. If this is true, $number is returned. 8 foreach ( @sampleValues ) { 9 print "fibonacci( $_ ) = ", fibonacci( $_ ), "\n"; If $number is greater than 1, the recursion step generates two recursive calls, each of which is a slightly simpler problem than the original call to fibonacci. 10 } 11 12 # fibonacci recursively calculates the fibonacci number 13 # of its integer argument 14 sub fibonacci 15 { 16 my $number = shift; # get the first argument 17 18 if ( $number == 0 or $number == 1 ) { # base case 19 return $number; 20 } 21 22 else { # recursive step 23 return fibonacci( $number - 1 ) + 24 fibonacci( $number - 2 ); 25 } 26 }

  24. fibonacci( 0 ) = 0 fibonacci( 1 ) = 1 fibonacci( 2 ) = 1 fibonacci( 3 ) = 2 fibonacci( 4 ) = 3 fibonacci( 5 ) = 5 fibonacci( 6 ) = 8 fibonacci( 10 ) = 55 fibonacci( 20 ) = 6765 fibonacci( 30 ) = 832040 fibonacci( 35 ) = 9227465

  25. Fig. 6.15 Set of recursive calls to subroutine fibonacci.

  26. 1 #!/usr/bin/perl 2 # Fig. 6.16: fig06_16.pl 3 # Demonstrating variable scope. Calls subroutine1 before any global variables are defined. This subroutine defines a lexical variable $x and initializes it to 10, and defines a dynamic variable $y and initializes it to 5. 4 Keyword our explicitly defines a variable as a global variable. 5 # before global variables are defined, call subroutine1 6 print "Without globals:\n"; The local keyword applied to $y actually creates a temporary copy of the global variable. The old value is saved while there is a new value in $y. This new value exists until the end of the current block (i.e., subroutine1’s body), at which point the old value is restored. Calls subroutine1 (its output is the same as the first time it was called). Notice that subroutine1 uses its own definitions of $x and $y, rather than the global definitions. 7 subroutine1(); 8 9 # define global variables Keyword my defines a lexically scoped variable. 10 our $x = 7; 11 our $y = 17; 12 13 # call subroutine1 to see results with defined global variables 14 print "\nWith globals:"; 15 print "\nglobal \$x: $x"; 16 print "\nglobal \$y: $y\n"; 17 subroutine1(); 18 print "\nglobal \$x: $x"; 19 print "\nglobal \$y: $y\n"; 20 21 # subroutine1 displays its own $x (lexical scope ) 22 # and $y (dynamic scope) variables, then calls subroutine2 23 sub subroutine1 24 { 25 my $x = 10; 26 local $y = 5; 27 print "\$x in subroutine1: $x\t(lexical to subroutine1)\n"; 28 print "\$y in subroutine1: $y\t(dynamic to subroutine1)\n"; 29 subroutine2(); 30 }

  27. 31 32 # subroutine2 displays global $x and subroutine1's $y which 33 # has dynamic scope 34 sub subroutine2 subroutine2 can “see” the local $y declaration from subroutine1, because subroutine1 has not terminated yet. When subroutine1 does finally terminate, the original value is restored and the remainder of the program can access it. 35 { 36 print "\$x in subroutine2: $x\t(global)\n"; 37 print "\$y in subroutine2: $y\t(dynamic to subroutine1)\n"; 38 } Without globals: $x in subroutine1: 10 (lexical to subroutine1) $y in subroutine1: 5 (dynamic to subroutine1) $x in subroutine2: (global) $y in subroutine2: 5 (dynamic to subroutine1) With globals: global $x: 7 global $y: 17 $x in subroutine1: 10 (lexical to subroutine1) $y in subroutine1: 5 (dynamic to subroutine1) $x in subroutine2: 7 (global) $y in subroutine2: 5 (dynamic to subroutine1) global $x: 7 global $y: 17

  28. 1 #!usr/bin/perl 2 #Fig. 6.17: fig06_17.pl 3 # Demonstrating packages. 4 Declares a main package variable named $variable and assigns it the string "happy". 5 # make FirstPackage.pm available to this program Uses keyword require to tell Perl to locate FirstPackage.pm and add it to the program. Implicitly searches for $variable in the current package (i.e., main). 6 require FirstPackage; Uses $variable’s fully qualified name, in which the package and the variable names are joined by the double colon operator (::). 7 8 # define a package global variable in this program 9 our $variable = "happy"; Attempts to display the value of the lexical variable $secret in FirstPackage. Notice that nothing is displayed in this case. Remember, lexical variables can be accessed only in the block or file in which they are originally defined. Displays the contents of the variables in FirstPackage by calling function displayFirstPackageVariables. Displays the value of $FirstPackage::variable. 10 11 # display values from the main package 12 print "From main package:\n"; 13 print "\$variable = $variable\n"; 14 print "\$main::variable = $main::variable\n"; 15 16 # display values from FirstPackage 17 print "\nFrom FirstPackage:\n"; 18 print "\$FirstPackage::variable = $FirstPackage::variable\n"; 19 print "\$FirstPackage::secret = $FirstPackage::secret\n"; 20 21 # use a subroutine in FirstPackage to display the 22 # values of the variables in that package 23 FirstPackage::displayFirstPackageVariables();

  29. 24 #!usr/bin/perl 25 # Fig 6.18: FirstPackage.pm 26 # Our first package. The package definition tells Perl that all variable and subroutine definitions for the remainder of that file (or until the next package statement) are in the FirstPackage package (or namespace). The package contains three identifiers—package global variable $variable, lexical variable $secret and subroutine displayFirstPackageVariables . 27 28 package FirstPackage; # name the package/namespace 29 30 # define a package global variable 31 our $variable = "birthday"; 32 33 # define a variable known only to this package 34 my $secret = "new year"; 35 36 # subroutine that displays the values of 37 # the variables in FirstPackage 38 sub displayFirstPackageVariables 39 { 40 print "\$variable in displayFirstPackageVariables = ", 41 $variable, "\n"; 42 print "\$secret in displayFirstPackageVariables = ", 43 $secret, "\n"; 44 } From main package: $variable = happy $main::variable = happy From FirstPackage: $FirstPackage::variable = birthday $FirstPackage::secret = $variable in displayFirstPackageVariables = birthday $secret in displayFirstPackageVariables = new year

  30. 1 #!/usr/bin/perl 2 # Fig 6.19: fig06_19.pl 3 # program to use our first module 4 5 use FirstModule; # import identifiers from another package Calls subroutine greeting from module FirstModule. Imports module FirstModule. 6 Displays the contents of @array from module FirstModule. 7 print "Using automatically imported names:\n"; 8 print "\@array contains: @array\n"; # @FirstModule::array 9 greeting(); # FirstModule::greeting Using automatically imported names: @array contains: 1 2 3 Modules are handy!

  31. 10 #!/usr/bin/perl Indicates that the current module uses the Exporter module. 11 # Fig 6.20: FirstModule.pm 12 # Our first module. 13 14 package FirstModule; 15 Indicates that the special built-in array @ISA contains Exporter. 16 # the following two lines allow this module to export its Definitions of the variables and subroutines that can be imported into another program’s namespace. Adds items to the special built-in array @EXPORT. In this case, array @array and subroutine &greeting will be available to any program that uses this module. 17 # identifiers for use in other files. 18 use Exporter; # use module Exporter 19 our @ISA = qw( Exporter ); # this module "is an" Exporter 20 21 # @array and &greeting are imported automatically into a 22 # file that uses this module 23 our @EXPORT = qw( @array &greeting ); 24 25 # define identifiers for use in other files 26 our @array = ( 1, 2, 3 ); 27 28 sub greeting 29 { 30 print "Modules are handy!"; 31 } 32 33 33 return 1; # indicate successful import of module

More Related