Questions And Answers

More Tutorials

Subroutines and Functions

Subroutines are defined in Perl as:

sub subname {

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:

You may use the explicit return statement to return a value and leave the subroutine at any point.
sub myfunc {
if (condition) return $val;
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;
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.


In this page (written and validated by ) you learned about Perl Subroutines and Functions . What's Next? If you are interested in completing Perl tutorial, your next topic will be learning about: Perl Files handling.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.