Perl 05 Subroutines
Perl 05 Subroutines
boss
worker4 worker5
exp( -2 ): 0.135335283236613
log( 5 ): 1.6094379124341
sqrt( 16 ): 4
User Defined Subroutines
User defined subroutines are defined using the key
word “sub” followed by the name of the subroutine.
We do
Were
notdo
have
we the
define
concept
the of
subroutine
subroutine?
prototype.
1 #!/usr/bin/perl
2 #
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 }
called subroutine1
called subroutine2
Argument List
The list of arguments passed to a subroutine are
stored in the special array variable @_.
Returned: hello
If so how
Other Ways To Invoke a Subroutine
A subroutine could be defined either in the beginning
or at the end of the Perl program.
------------------------------
Subroutines defined before use
------------------------------
Using & and ():
definedBeforeWithoutArguments
definedBeforeWithArguments: 1 2 3
Using bareword:
definedBeforeWithoutArguments
definedBeforeWithArguments: 1 2 3
-----------------------------
Subroutines defined after use
-----------------------------
Using & and ():
definedAfterWithoutArguments
definedAfterWithArguments: 1 2 3
Using bareword:
"definedAfterWithoutArguments" causes no action
"definedAfterWithArguments 1, 2, 3" generates a syntax error
rand( ) and srand( ) Functions
The function rand( ) generates a floating-point scalar
value greater than or equal to 0 and less than 1.
Setting seed to 1
1 4 2
Setting seed to 1
1 4 2
Resetting seed
2 * 1! 2 * 1!
1 returned
1 1
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 ) return 1
return 1 return 0
Can
Howwedo have
we resolve
two or name
more
subroutine conflict
with the?same name
Package or Namespace
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 specified
package (or namespace).
A package is defined using the key word package,
followed by the name of the package.
Uses keyword require to tell Perl to locate the
package and add it to the program.
The fully qualified name, in which the package and
the variable names are joined by the double colon
operator (::).
require Compiler Directive
The require directive is used to load Perl libraries.
require FirstPackage;
From FirstPackage:
$FirstPackage::variable = birthday
$FirstPackage::secret =
$variable in displayFirstPackageVariables = birthday
$secret in displayFirstPackageVariables = new year