Chapter 6 - Subroutines and Functions

Slides:



Advertisements
Similar presentations
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
Advertisements

Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Scripting Languages Perl Chapter #4 Subroutines. Writing your own Functions Functions is a programming language serve tow purposes: –They allow you to.
 2007 Pearson Education, Inc. All rights reserved C Functions.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 12 – Craps Game Application: Introducing Random.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
1 Lecture 3 Part 1 Functions with math and randomness.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - JavaScript: Functions Outline 10.1 Introduction 10.2 Program Modules in JavaScript 10.3.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
 2005 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 5: Functions Xiang Lian The University of Texas – Pan American Edinburg, TX
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Craps Game Application Introducing Random-Number Generation and Enum.
 2000 Prentice Hall, Inc. All rights reserved. 5.2Program Modules in C Functions –Modules in C –Programs combine user-defined functions with library functions.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Introduction Program Components in C++ Math Library Functions Functions.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Chapter 9: Value-Returning Functions
Functions Course conducted by: Md.Raihan ul Masood
User-Written Functions
Chapter 6: User-Defined Functions I
Functions and an Introduction to Recursion
Chapter 4 C Program Control Part I
Chapter 3 - Functions Outline 3.1 Introduction
Chapter 2 - Introduction to C Programming
Methods Chapter 6.
© 2016 Pearson Education, Ltd. All rights reserved.
Chapter 5 - Control Structures: Part 2
The Selection Structure
JavaScript: Functions
CSC113: Computer Programming (Theory = 03, Lab = 01)
Deitel- C:How to Program (5ed)
JavaScript: Functions.
Chapter 2 - Introduction to C Programming
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
User-Defined Functions
Chapter 10 - JavaScript: Functions
Formatted and Unformatted Input/Output Functions
Chapter 5 - Functions Outline 5.1 Introduction
توابع در C++ قسمت اول اصول كامپيوتر 1.
Chapter 2 - Introduction to C Programming
Introduction to C++ Programming
Chapter 6 - Functions Outline 5.1 Introduction
Chapter 2 - Introduction to C Programming
PHP.
Chapter 2 - Introduction to C Programming
Chapter 6: User-Defined Functions I
Function.
Chapter 2 - Introduction to C Programming
COMPUTER PROGRAMMING SKILLS
Subroutines.
6 Functions.
Function.
Functions in C Math Library Functions Functions Function Definitions
Presentation transcript:

Chapter 6 - Subroutines and Functions Outline 6.1 Introduction 6.2 Subroutines in Perl 6.3 Built-in Math Functions 6.4 User-defined Subroutines 6.5 Argument Lists 6.6 Returning Values 6.7 Other Ways to Invoke a Subroutine 6.8 Random-Number Generators 6.9 Example: A Game of Chance 6.10 Recursion 6.11 Example Using Recursion 6.12 Recursion vs. Iteration

Chapter 6 - Subroutines and Functions Outline 6.13 Scope Rules: Global, Lexical and Dynamic 6.14 Namespaces, Packages and Modules 6.14.1 Defining a Package and Importing it with require 6.14.2 Modules and the use Statement 6.14.3 Other Features of the use Statement 6.15 Pragmas

Fig. 6.1 Hierarchical boss–subroutine/worker–subroutine relationship.

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

This line calls (or invokes) subroutine2. 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 6 subroutine2(); # call the subroutine with no arguments 7 8 # the code after this comment executes only if the program 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 } 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. When it is called, the body of the subroutine executes to perform the subroutine’s task (display the string "called subroutine1\n"). When it is called, the body of the subroutine executes to perform the subroutine’s task (display the string "called subroutine2\n"). called subroutine1 called subroutine2

1 #!/usr/bin/perl 2 # Fig 6.5: fig06_05.pl 3 # Demonstrating a subroutine that receives arguments. 4 5 displayArguments( "Sam", "Jones", 2, 15, 73, 2.79 ); 6 7 # output the subroutine arguments using special variable @_ 8 sub displayArguments 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 } This line calls subroutine displayArguments with six string and numeric arguments. Displays the contents of the entire arguments array with each argument separated by a space. 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. 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

Displays the squared value followed by a space. 1 #!/usr/bin/perl 2 # Fig 6.6: fig06_06.pl 3 # Demonstrating a subroutine that returns a value. 4 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( $_ ), " "; 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 } 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, @_. Subroutine square, which calculates the square of the value the subroutine receives as its argument. Displays the squared value followed by a space. Function shift, when used without any arguments, operates on the @_ special array variable and removes the first element of the array. Evaluates the expression $value ** 2 (the square of $value) and passes the result back to the caller via the return keyword. 1 4 9 16 25 36 49 64 81 100

1 #!/usr/bin/perl 2 # Fig 6.7: fig06_07.pl 3 # Demonstrating a subroutine that returns a scalar or a list. 4 5 # call scalarOrList() in list context to initialize @array, 6 # then print the list 7 @array = scalarOrList(); # list context to initialize @array 8 $" = "\n"; # set default separator character 9 print "Returned:\n@array\n"; 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 } Uses the return value of scalarOrList to initialize @array. This is a list context. 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. 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. Uses the return value of scalarOrList in a string-concatenation operation. This is a scalar context.

Returned: this is a list of strings   Returned: hello

Call subroutines with both & and (). 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"; 9 } 10 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 Call subroutines with both & and (). Call subroutines with the common () notation.

29 print "\nUsing only &:\n"; 30 &definedBeforeWithoutArguments; 31 print "\"&definedBeforeWithArguments 1, 2, 3\"", 32 " generates a syntax error\n"; 33 34 print "\nUsing bareword:\n"; 35 definedBeforeWithoutArguments; 36 definedBeforeWithArguments 1, 2, 3; 37 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 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. Subroutines that are defined after they are used in the program are invoked correctly when using & and () or when using just (). 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. The subroutine with arguments is not called, because it would cause a syntax error.

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 (): Using only &: "&definedBeforeWithArguments 1, 2, 3" generates a syntax error Using bareword:

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

1 #!usr/bin/perl 2 # Fig. 6.9: fig06_09.pl 3 # Demonstrating function rand. 4 5 print "Random numbers produced by rand():\n"; 6 7 for ( 1 .. 3 ) { 8 print " ", rand(), "\n"; 9 } 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 } The function rand generates a floating-point scalar value greater than or equal to 0 and less than 1. 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. 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.

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

1 #!/usr/bin/perl 2 # Fig. 6.10: fig06_10.pl 3 # Seeding the random number generator. 4 5 # during each iteration, set seed to 1, 6 # then produce three random integers 7 for ( 1 .. 3 ) { 8 print "\n\nSetting seed to 1\n"; 9 srand( 1 ); 10 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"; 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. The sequence of pseudorandom numbers repeats itself each time the seed is set to the same value. This causes the computer to read its system clock to obtain the value for the seed automatically. This is the default behavior for srand. By allowing the system to determine the seed, different sets of random values are generated each time.

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

1 #!/usr/bin/perl 2 # Fig. 6.11: fig06_11.pl 3 # The game of Craps. 4 5 $roll = rollDice(); # start the game 6 7 # determine if the game is a win or loss, 8 # or if the game should continue 9 if ( $roll == 7 or $roll == 11 ) { # won? 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 } The game begins by calling subroutine rollDice to roll the dice, compute and print their sum and return the sum. 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. 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". Each iteration of the while loop calls rollDice to produce a new $roll. 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.

31 32 print message( $status ); # display message with result 33 34 # subroutines to support the game of craps 35 36 # rollDice rolls two dice and returns the sum of the dice 37 sub rollDice 38 { 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 } Subroutine rollDice rolls the dice, computes and prints their sum and returns the sum. Subroutine rollDie is called by rollDice to generate a random number from 1 through 6. Subroutine message takes a single argument (WON or LOST) and returns an appropriate message indicating whether the game was won or lost.

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.

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

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 6 # 0 through 10 and display the results 7 foreach ( 0 .. 10 ) { 8 print "$_! = " . factorial( $_ ) . "\n"; 9 } 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 } 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. 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.

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

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 8 foreach ( @sampleValues ) { 9 print "fibonacci( $_ ) = ", fibonacci( $_ ), "\n"; 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 } Each fibonacci call immediately tests for the base case—$number equal to 0 or 1. If this is true, $number is returned. 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.

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

Fig. 6.15 Set of recursive calls to subroutine fibonacci.

Keyword our explicitly defines a variable as a global variable. 1 #!/usr/bin/perl 2 # Fig. 6.16: fig06_16.pl 3 # Demonstrating variable scope. 4 5 # before global variables are defined, call subroutine1 6 print "Without globals:\n"; 7 subroutine1(); 8 9 # define global variables 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 } 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. Keyword our explicitly defines a variable as a global variable. 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. Keyword my defines a lexically scoped variable.

31 32 # subroutine2 displays global $x and subroutine1's $y which 33 # has dynamic scope 34 sub subroutine2 35 { 36 print "\$x in subroutine2: $x\t(global)\n"; 37 print "\$y in subroutine2: $y\t(dynamic to subroutine1)\n"; 38 } 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. 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 subroutine2: 7 (global)

Implicitly searches for $variable in the current package (i.e., main). 1 #!usr/bin/perl 2 #Fig. 6.17: fig06_17.pl 3 # Demonstrating packages. 4 5 # make FirstPackage.pm available to this program 6 require FirstPackage; 7 8 # define a package global variable in this program 9 our $variable = "happy"; 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(); Uses keyword require to tell Perl to locate FirstPackage.pm and add it to the program. Declares a main package variable named $variable and assigns it the string "happy". Implicitly searches for $variable in the current package (i.e., main). Uses $variable’s fully qualified name, in which the package and the variable names are joined by the double colon operator (::). Displays the value of $FirstPackage::variable. 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.

24 #!usr/bin/perl 25 # Fig 6.18: FirstPackage.pm 26 # Our first package. 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 } 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 . From main package: $variable = happy $main::variable = happy   From FirstPackage: $FirstPackage::variable = birthday $FirstPackage::secret = $variable in displayFirstPackageVariables = birthday $secret in displayFirstPackageVariables = new year

Imports module FirstModule. 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 6 7 print "Using automatically imported names:\n"; 8 print "\@array contains: @array\n"; # @FirstModule::array 9 greeting(); # FirstModule::greeting Imports module FirstModule. Displays the contents of @array from module FirstModule. Calls subroutine greeting from module FirstModule. Using automatically imported names: @array contains: 1 2 3 Modules are handy!

Indicates that the current module uses the Exporter module. 10 #!/usr/bin/perl 11 # Fig 6.20: FirstModule.pm 12 # Our first module. 13 14 package FirstModule; 15 16 # the following two lines allow this module to export its 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 Indicates that the current module uses the Exporter module. Indicates that the special built-in array @ISA contains Exporter. 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. Definitions of the variables and subroutines that can be imported into another program’s namespace.