Skip to Content
Beginning Perl
book

Beginning Perl

by Curtis Ovid Poe
September 2012
Beginner
744 pages
15h 48m
English
Wrox
Content preview from Beginning Perl

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Perl

Mastering Perl

brian d foy
Learning Perl 6

Learning Perl 6

brian d foy
Perl & LWP

Perl & LWP

Sean M. Burke
Perl by Example

Perl by Example

Ellie Quigley

Publisher Resources

ISBN: 9781118235638Purchase book