Subroutines

Subroutines are sections of code seperated from the rest of the script that can be called on to carry out a certain task, repeatedly if necessary. By moving a significant sequence of operations into a subroutine, you can save time and space since yo u only having to write down these instructions once. Using subroutines can also simplify the understanding of the rest of your code by making it less cluttered.

Subroutines have access to all the variables in the normal section of your code. In that sense, your variables are global.


Creating a subroutine

While subroutines can be defined anyway in your script file, it's common practice to place them in your file after the main body of code. A subroutine consists of the keyword sub followed by a name for the subroutine and then a sequence of instructions to be executed enclosed in braces.

sub sub_routine_name {
# Sequence of instructions to be executed
# when the subroutine is called

}


Calling a subroutine


You cause a subroutine to be executed by using its name followed by paretheses as a command statement:

Example:

# Main Body of Code

$a = <STDIN>;
if($a eq "secret word"){
	grant_access();
}

# Subroutine Defintion for grant_access()

sub grant_access(){
	# Some statements go here giving
	# the user access 
}


Returning a value

Optionally, a subroutine can define places where it halts execution and returns a value to the place in your main body of code that called it.

$a = <STDIN>;
print $a . " is " . compare_to_zero() . "\n";

sub compare_to_zero {
	if($a > 0){
		return "greater than zero";
	}
	elsif($a == 0) {
		return "equal to zero";
	else{
		return "less than zero";	
	}
}

If the input = 4, then the output will be:

4 is greater than zero

If you do not include a return statement in your subroutine, or the subroutine finishes without hitting a return statement, the subroutine end when its last statement is executed. It will return a value equal to the last expression evaluated.

Example:

$a = 5;
print add_10();

sub add_10 {
	$a = $a +10;
}

Output:

15


Other features of subroutines

There are other things you can do with subroutines such as passing parameters and using local variables. We'll talk about those feataures a little later.