As with most things, subroutines get more useful as they get more complicated. For the most
part, unless you're programming your own scripts, you'll never need to touch them.
The most useful subroutines have scalar variables passed to them. They then
do something to the variables, such a perform calculations, format, etc. and return the result.
For example, let's say you wanted to convert degrees Fahrenheit to Celsius. You can pass Fahrenheit
to a subroutine, let the subroutine perform the proper conversion calculation, and give the Celsius back
to the program. Let's see it in use.
Running the program will print the following:
95 degrees Fahrenheit is 35 degrees Celsius.
The line-by-line.
#!/usr/bin/perl
This first line tells the program where to find the perl interpreter.
$fahrenheit = 95;
Here, we're defining $fahrenheit as 95.
$celsius = &convert($fahrenheit);
Here, we're saying that $celsius is equal to the result of the "convert"
subroutine using the value of $fahrenheit. The
$fahrenheit in parenthesis immediately after the
&convert tells perl to use the value of $fahrenheit
in the subroutine. Called "passing variables" to the subroutine, this allows you to use one subroutine
from different parts of your program without duplicating the code.
print "$fahrenheit degrees Fahrenheit is $celsius degrees Celsius.\n";
Because the previous line acquired the value of $celsius, here we print the result.
sub convert {
Names and opens the subroutine.
my $fahr = $_[0];
Tells perl to use assign $fahr to the first value passed to the subroutine
($fahrenheit). Remember that perl starts counting at zero.
my $cels = ($fahr - 32) * 5/9;
This assigns $cels with the result of the Fahrenheit to Celsius equation.
return $cels
This line tells perl to return the value of $cels back to the point
where this subroutine was invoked. Referring back to $celsius =
&convert($fahrenheit) now $celsius equals
$cels.
}
Closes the subroutine.
Now let's say you needed to convert the degrees Fahrenheit to Celsius for the past 5 days. You can reuse
the same subroutine for each day. Let's take a look...
The result of running this program is:
Mon was 37.2222222222222 degrees Celsius.
Tue was 33.3333333333333 degrees Celsius.
Wed was 35 degrees Celsius.
Thu was 30.5555555555556 degrees Celsius.
Fri was 28.3333333333333 degrees Celsius.
(It's important to note that this by far isn't the best way to write a multi-day/variable program,
but I strove to demonstrate the efficiency of subroutines without introducing too many new concepts).
As you can see, this "modular" use of subroutines increases program efficiency and overall usability.