If a set of statements are to be executed many times according to the requirements, the statements are enclosed in a function or subroutine.
In Perl the words, subroutine, method and function, are used interchangeably.
Subroutine Definition and Call
A subroutine is called by it's name as
subroutine_name(list of arguments);
In old version of perl, subroutine is called as
&subroutine_name( list of arguments );
Perl compiles programs before executing it, hence, location of subroutine definition does not matter. Let's have a look into the following example.
Passing Arguments to a Subroutine
Various arguments can be passed to a subroutine. These arguments
are acessed inside the function like an array using
@_
.
Let's try the following example, which takes a list of numbers and then prints their average
Passing Lists to Subroutines
@_
can be used to pass lists to a subroutine. But extraction of the
individual elements are difficult. Let's try the following program.
Passing Hashes to Subroutines
A hash is automatically translated into a list of key/value pairs when it is passed as argument. Let's try the following example.
Returning Value from a Subroutine
You can return a value from subroutine like you do in any other programming language. If a value is not returned from a subroutine then subroutine automatically returns value we have updated in it.
Similar to array and hash passing in a subroutine, if they are returned from the subroutine their separate identities are lost.
Let's try the following example.
Private Variables in a Subroutine
By default, all variables in Perl are global variables, which can
be accessed from anywhere in the program. If a private variable
(lexical variables) is needed, it can be created using
my
operator.
The block where a private variable is declared, the block becomes it's scope. Such as the body of the subroutine or those marking the code blocks of if, while, for, foreach, and eval statements.
The scope of a variable is shown in the following sample code.
Let's check the following example.
Temporary Values via local()
In case of local, the current value of a variable must be visible to called subroutines. This is known as dynamic scoping.
If more than one variable or expression is given to local, they must be placed in parentheses.
Let's check the following example.
State Variables via state()
These are private variables but they maintain their state, upon multiple calls of the subroutines.
Let's check the following example.
Subroutine Call Context
The context of a subroutine or statement is defined as the type of
return value that is expected. For example, in
my $str = localtime( time );
a string is returned as it is in scalar context. Whereas in
($sec,$min,$hour,$mday,$mon, $year,$wday,$yday,$isdst) =
localtime(time);
, the values are stored in different variables.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.