Subroutines and functions save time by letting you reuse code. This six-part series will show you how to create and use them in Perl. This article was excerpted from chapter six of the book Beginning Perl, Second Edition, written by James Lee (Apress; ISBN: 159059391X).
Now that we know what subroutines are, it’s time to look at how to define them and how to use them. First, let’s see how to create subroutines.
Defining a Subroutine
We can give Perl some code, and we can give it a name, and that’s our subroutine. Here’s how we do it:
sub example_subroutine { ... }
There are three sections to this declaration:
The keywordsub.
The name we’re going to give it. The rules for naming a subroutine are exactly those for naming variables; names must begin with an alphabetic character or an underscore, to be followed by zero or more alphanumerics or underscores. Uppercase letters are allowed, but we tend to reserve all-uppercase names for special subroutines. And again, as for variables, you can have a scalar$fred, an array@fred, a hash %fred, and a subroutinefred(), and they’ll all be distinct.
A block of code delimited by curly braces, just as we saw when we were usingwhileandif. Notice that we don’t need a semicolon after the closing curly brace.
After we’ve done that, we can use our subroutine.
Before we go any further though, it’s worth taking a quick time-out to ponder how we name our subroutines. You can convey a lot about a subroutine’s purpose with its name, much like that of a variable. Here are some guidelines—not hard-and-fast rules—about how you should name subroutines:
If they’re primarily about doing something, name them with a verb—for example,summarize()ordownload().
If they’re primarily about returning something, name them after what they return—for example,greeting()orheader().
If they’re about testing whether something is true or not, give them a name that makes sense in anifstatement; starting withis_...orcan_...helps, or if that isn’t appropriate, name them with an adjective: for example,is_available(),valid(), orreadable().
Finally, if you’re converting between one thing and another, try and convey both things— traditionally this is done with a2or_to_in the middle:text2html(),meters_to_feet(). That way you can tell easily what’s being expected and what’s being produced.