Home » Perl Basics
name-of-your-subroutine ();
Subroutines should be used any time you have a code that will be reused. Subroutines also accept arguments so you can tell the subroutine what to analyze.
You can also print all the element of the $_ variable
print “$_”;
5
Subroutines
Subroutines help to organize your code
A subroutine will allow you to organize your code so it is more readable and grouped in a logical manner. It will also save you time as you will reuse the subroutine throughout the code without having to rewrite the whole code.
Code Header Variable declaration Subroutine1 Subroutine2 Etc… Main code Call subroutine1 Call subroutine2 Code Code Call subroutine2 Code Call subroutine1 End of code
Aside from being readable, your code will also be easily modifiable as you will not need to edit deep inside the code every time you use a specific function. Simply make a subroutine of it and change it once.
Creating a subroutine is very easy and is reminiscent of the syntax of a block.
Sub name-of-your-subroutine {
Your code
}
To call a subroutine within your codename-of-your-subroutine ();
Subroutines should be used any time you have a code that will be reused. Subroutines also accept arguments so you can tell the subroutine what to analyze.
Name-of-your-subroutine(“ argument1”);
Sub name-of-your-subroutine {
print “$_[0]”;
}
$_[] is a array type variable maintained by the system that will store the argument you pass to the subroutine. As for arrays the first argument pasted is $_[0} the second $_[1] etc..You can also print all the element of the $_ variable
print “$_”;