|
12 Subroutines
sub
mysubroutine
# Example: sub yesno
BLOCK
# Note no arguments listed in the "sub" line
{
print
"you made it!"
;
}
# there is no fixed number of arguments
To call a subroutine:
$mysubroutine
();
# ok anywhere in the Perl code
-
or
-
mysubroutine();
# if sub was already defined in the code
-
or
-
$mysubroutine
(
$var1
, 23.5,
"mother"
)
# includes arguments
-
or
-
$mysubroutine
$var1
, 23.5,
"mother"
# without () if sub already seen
Returning a value: all subroutines
return
a single value
-
can be
scalar
, array, assoc array
default is to
return
the
last
expression
's value
-
or
-
return
(expression)
# example: return ($temp) --> return a scalar value
# example: return (0) --> return a specific value
# example: return (@myarray) --> return an array
sub
test
{
print
"hi"
$result
;
# to clarify return value, put the value to be returned on the last line
}
Pass
values
to subroutine:
$mysubroutine
(
$var1
, 23.5,
"mother"
)
# includes arguments
Retrieve returned
values
:
@_
is an array that has all the passed arguments
To simplify access to
@_
,
use
: (
$a
,
$b
,
$c
)
=
@_
To simplify as above, pass
scalar
variables first, then array
You can effectively pass only 1 array to
sub
(
and
keep it distinct)
$_
[0] is the 0th element of the array
@_
$_
[2] has nothing to
do
with
scalar
special variable
$_
if
you change a value of
@_
, the passed argument changes also
To retrieve multiple arrays,
use
references
Pure function: can be used by another program without relying on context it
's being called in
Subroutine example:
#!/usr/local/bin/perl
#
# Declare and Define subrouting MY_SUB
# call MY_SUB three times
#
# subroutine MY_SUB
#
sub
MY_SUB
{
local
(
$param_1
,
$param_2
)
=
@_
;
print
"
\n
Called MY_SUB
\n
\t
$param_1
\n
\t
$param_2
\n
"
;
}
#
# MAIN part of the program
#
for
(
$i
=
0;
$i
<
3;
$i
++
)
{
&MY_SUB (
"text"
, 123 ) ;
}
#
# DONE
#
|