1/13/2022

Functions / Subroutines in PERL


 In this article we will learn what is a PERL Subroutine through the below sections :

  •  Subroutines / Functions in PERL
  •  Declaration & Definition of Subroutines
  •  Passing & Receiving Arguments
  •  Call by Value
  •  Call by Reference 
  • Variable & Fixed Arguments 
  • Private & Temporary Variables
  • Built In Functions in PERL.


Subroutines/Functions in PERL : 

  • Like many programming languages, Perl provides user-defined subroutines (a.k.a function). 
  • These may be located anywhere in the main program.
  • Subroutines defined in separate files can be loaded via the do, require, or use keywords.
  • A function/subroutine can be called by reference using a CODE reference variable.
  • Placement may be before or after main program text (after is preferred).
  • No type associated with function name.
  • No argument list given with function definition.
  • No local subroutines. If there are two with the same name then the 1st is overwritten.
  • In general a function without an explicit return statement is called a subroutine.
  • There's really no difference from Perl's perspective.
  • Return statement - very similar to C++ .
  • Type of data returned is relaxed, as function has no type associated.
  • May return a scalar or a list.

Declaration & Definition of Subroutine in PERL :

The subroutine Declaration is done at the  beginning of the code as :


At later part of the code i.e. after the MAIN section of the code , the explicit/inflated  definition is described :

Passing and Receiving Arguments :

Arguments are passed in form of a list/array with parentheses.

Example:  my $sum = add(2,7);

Inside the body of the function , arguments are received via a special variable name: the @_ array

$_[0] has the first argument, $_[1] has the second,  and so on .....

$#_ has the subscript of the last argument

undef is given to values beyond the end of the @_ array.

Subroutines : Call by Value : Understand By Examples :

Here is a example of calling a void function/subroutine :

hello(); # called as a void function

We define two variable & swap their values through a subroutine. 

my $x = "first";

my $y = "last";

swap($x, $y); # $x will be "last" and $y will be "first"

We have not shown the internal code of swap function/subroutine.

In the below example we get the max out of the to arguments in the scalar in the LHS.

my $a = max(2,3); # a will get 3

We can use a function/subroutine directly inside a print statement as :

print max(2,3) + max(4,5); # it prints 8

Subroutines : Call by Reference : Understand By Examples :

We can create a Anonymous Function which we can later call by reference. Also once we write a regular function , later we call it by reference. Both the form are shown below through a easy code.

Which upon execution gives the below output :


By looking at the output you can easily understand that both call-by-reference happen successfully.

Subroutine with Variable Arguments :

So far we have seen the functions/subroutines with fixed number of arguments in this articles.

In the below code example we have defined a subroutine to accept any number of arguments and so the addition of all the arguments. 

Run the code at your end and see the obvious output.

Subroutine with Fixed Arguments But Multiple Return Values :

In this code-example we have modular subtraction function implemented which only outputs the numerical difference between two numbers.

Run the code at your end and see the obvious output.

Private Variables by Using “my” in Subroutine Blocks :

When we use inside a subroutine block :

my $foo;            # declare $foo lexically local

my (@wid, %get);    # declare list of variables local

my $foo = "flurp";  # declare $foo lexical, and init it

my @oof = @bar;     # declare @oof lexical, and init it

Temporary Values by “local” in Subroutines :

When we use inside a subroutine block:

local $foo;                # make $foo dynamically local

local (@wid, %get);        # make list of variables local

local $foo = "flurp";      # make $foo dynamic, and init it

local @oof = @bar;         # make @oof dynamic, and init it

local $hash{key} = "val";  # sets a local value for this hash entry

delete local $hash{key};   # delete this entry for the current block

Built In Functions in PERL :

PERL has a lot of pre-built function/subroutines and yu must not use these names for your custom subroutines. Rather feel free to use them whenever you need :

#Numeric functions

abs, atan2, cos, exp, hex, int, log, oct, rand, sin, sqrt, srand

#Functions for list data

grep, join, map, qw//, reverse, sort, unpack

#Functions for real @ARRAYs

each, keys, pop, push, shift, splice, unshift, values

#Functions for real %HASHes

delete, each, exists, keys, values

#Functions for filehandles, files, or directories

-X, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link, lstat, mkdir, open, opendir, readlink, rename, rmdir, select, stat, symlink, sysopen, umask, unlink, utime

#Functions for SCALARs or strings :

chomp, chop, chr, crypt, fc, hex, index, lc, lcfirst, length, oct, ord, pack, q//, qq//, reverse, rindex, sprintf, substr, tr///, uc, ucfirst, y///

#Regular expressions and pattern matching

m//, pos, qr//, quotemeta, s///, split, study


The entire article is well narrated in the below Video :