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.
sub subName{ body }
The syntax for Perl define a subroutine function is given below:
sub subName{ body } OR subName(list of arguments); &subName(list of arguments);
In the following example, we are defining a subroutine function 'myOffice' and call it.
#defining function sub myOffice{ print "rookienerd!\n"; } # calling Function myOffice();
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.
$squarePerimeter = perimeter(25); print("This is the perimter of a square with dimension 25: $squarePerimeter\n"); sub perimeter { $dimension = $_[0]; return(4 * $dimension); }
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.
sub myList{ my @list = @_; print "Here is the list @list\n"; } @a = ("Orange", "Pineapple", "Mango", "Grapes", "Guava"); # calling function with list myList(@a);
When a hash is passed to a subroutine, then hash is automatically translated into its key-value pair.
sub myHash{ my (%hash) = @_; foreach my $key ( keys %hash ){ my $value = $hash{$key}; print "$key : $value\n"; } } %hash = ('Carla' => 'Mother', 'Ray' => 'Father', 'Ana' => 'Daughter', 'Jose' => 'Son'); # Function call with hash parameter myHash(%hash);
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).
$str = "AEIOU"; sub abc{ # Defining local variable my $str; $str = "AAABBBCCCDDD"; print "Inside the function local variable is called $str\n"; } # Function call abc(); print "Outside the function global variable is called $str\n";