Chapter 7
Subroutines
WHAT YOU WILL LEARN IN THIS CHAPTER:
- Declaringa subroutine
- Passing data to subroutines
- Returning data from subroutines
- Using prototypes
- Using subroutine references
- Understanding recursion
- Implementing error checking
WROX.COM CODE DOWNLOADS FOR THIS CHAPTER
The wrox.com code downloads for this chapter are found at http://www.wrox.com/WileyCDA/WroxTitle/Beginning-Perl.productCd-1118013847,descCd-DOWNLOAD.html on the Download Code tab. The code for this chapter is divided into the following major examples:
- example_7_1_running_total.pl
- example_7_2_length.pl
- example_7_3_zip.pl
- example_7_4_maze.pl
- listing_7_1_fibonacci.pl
- listing_7_2_binary_search.pl
A subroutine is just a way of providing a “name” to a piece of code. This is useful when you need to execute the same piece of code in several different places in your program, but you don’t want to just “cut-n-drool” the same code all over the place.
Even if you don’t want to reuse a piece of code, applying a name is useful. Compare the following two lines of code:
my $result = 1 + int( rand(6) );
my $result = random_die_roll();
Just by intelligently naming a subroutine, you can see that the second line of code much clearer than the first. Thus, you can use subroutines to make your code more self-documenting. As an added benefit, the name of a subroutine is documentation that you don’t forget to add.
SUBROUTINE SYNTAX
A basic subroutine (often just called a sub) is declared with the syntax of
sub IDENTIFIER BLOCK ...