Perl Functions and Subroutines

Perl functions and subroutines are used to reuse a code in a program. You can use a function at several places in your application with different parameters.

There is only one difference in function and subroutine, subroutine is created with sub keyword and it returns a value. You can divide your code into separate subroutines. Logically each function in each division should perform a specific task.

Syntax of subroutine:


Perl define and call subroutine function

The syntax for Perl define a subroutine function is given below:


In the following example, we are defining a subroutine function 'myOffice' and call it.

Output:

javaTpoint!

Perl subroutine Function with Arguments

You can pass any number of arguments inside a subroutine. Parameters are passed as a list in the special @_ list array variables. Hence, the first argument to the function will be $_[0], second will be $_[1] and so on.

In this example, we are calculating perimeter of a square by passing a single parameter.

Output:

100

Perl subroutine with List

Here the @_ variable is an array, hence it is used to supply list to a subroutine. We have declared an array 'a' with list and call it.

Output:

Here is the list Orange Pineapple Mango Grapes Guava

Perl subroutine with Hashes

When a hash is passed to a subroutine, then hash is automatically translated into its key-value pair.

Output:

Ray : Father
Jose : Son
Carla : Mother
Ana : Daughter

Perl subroutine Local and Global Variables

By default, all the variables are global variables inside Perl. But you can create local or private variables inside a function with 'my' keyword.

The 'my' keyword restricts the variable to a particular region of code in which it can be used and accessed. Outside this region, this variable can not be used.

In the following example, we have shown both local and global variable. First, $str is called locally (AAABBBCCCDDD) and then it is called globally (AEIOU).

Output:

Inside the function local variable is called AAABBBCCCDDD 
Outside the function global variable is called AEIOU