Defining a Subroutine

4.2 Defining a Subroutine

To define your own subroutine, use the keyword sub, the name of the subroutine (without the ampersand), then the indented[3] block of code (in curly braces) which makes up the body of the subroutine, something like this:

[3] Okay, purists, we admit it: the curly braces are part of the block, properly speaking. And Perl doesn't require the indentation of the block but your maintenance programmer will. So please be stylish.

sub marine {
  $n += 1;  # Global variable $n
  print "Hello, sailor number $n!\n";
}

Subroutine definitions can be anywhere in your program text, but programmers who come from a background of languages like C or Pascal like to put them at the start of the file. Others may prefer to put them at the end of the file, so that the main part of the program appears at the beginning. It's up to you. In any case, you don't normally need any kind of forward declaration.[4]

[4] Unless your subroutine is being particularly tricky and declares a "prototype," which dictates how a compiler will parse and interpret its invocation arguments. This is rare see the perlsubmanpage for more information.

Subroutine definitions are global; without some powerful trickiness, there are no private subroutines.[5] If you have two subroutine definitions with the same name, the later one overwrites the earlier one.[6] That's generally considered bad form, or the sign of a confused maintenance programmer.

[5] If you wish to be powerfully tricky, read the Perl documentation about coderefs stored in private (lexical) variables.

[6] A warnable offense, however.

As you may have noticed in the previous example, you may use any global variables within the subroutine body. In fact, all of the variables we've seen so far are globals; that is, they are accessible from every part of your program. This horrifies linguistic purists, but the Perl development team formed an angry mob with torches and ran them out of town years ago. We'll see how to make private variables in the section "Private Variables in Subroutines" later in this chapter.

 



Learning Perl
Learning Perl, 5th Edition
ISBN: 0596520107
EAN: 2147483647
Year: 2001
Pages: 205

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net