Sunday, 6 April 2014

PS_08_Perl - Subroutines and Functions

Subroutines and Functions

Subroutines are defined in Perl as:

        sub subname {
                statement_1;
                statement_2;
        }

Subroutine definitions are global; there are no local subroutines.

Invoking subroutines
The ampersand (&) is the identifier used to call subroutines. They may also be called by appended parentheses to the subroutine name:

        name();
        &name;

You may use the explicit return statement to return a value and leave the subroutine at any point.

        sub myfunc {
                statement_1;
                if (condition) return $val;
                        statement_2;
                return $val;
        }

Passing arguments
Arguments to a subroutine are passed as a single, flat list of scalars, and return values are passed the same way. Any arguments passed to a subroutine come in as @_. To pass lists of hashes, it is necessary to pass references to them:

        @returnlist = ref_conversion(\@inlist, \%inhash);

The subroutine will have to dereference the arguments in order to access the data values they represent.

        sub myfunc {
                my($inlistref,$inhashref) = @_;
                my(@inlist) = @$inlistref;
                my(%inhash) = %$inhashref;
                statements;
                return @result;
        }

Prototypes allow you to design your subroutines to take arguments with constraints on the number of parameters and types of data.

Variable Scope
Any variables used in a subroutine that aren’t declared private are global variables.
The my function declares variables that are lexically scoped within the subroutine. This means that they are private variables that only exist within the block or routine in which they are called. The local function declares variables that are dynamic. This means that they have global scope, but have temporary values within the subroutine. Most of the time, use my to localize variables within a subroutine.

No comments :

Post a Comment