`

Note of Learning Perl--Subroutines

    博客分类:
  • Perl
阅读更多

Subroutines
-----------------

1. System and User Functions
 1) The name of a subroutine is another Perl identifier (letters, digits, and underscores, but can't start with a digit) with a sometimes-optional ampersand (&) in front.
 2) That subroutine name comes from a separate namespace, so Perl won't be confused if you have a subroutine called &fred and a scalar called $fred in the same program.

2. Defining a Subroutine
 1) Subroutine definitions can be anywhere in your program text. In any case, you don't normally need any kind of forward declaration.
 2) Subroutine definitions are global; without some powerful trickiness, there are no private subroutines. If you have two subroutine definitions with the same name, the later one overwrites the earlier one.
 
3. Return Values
 1) The return value is the last expression evaluated in the body of a subroutine.
 2) If the last expression of a subrountine is the print statement. Its return value will normally be 1, meaning "printing was successful,"[104] but that's not the return value we actually wanted. So be careful when adding additional code to a subroutine to ensure that the last expression evaluated will be the desired return value.
 3) "The last expression evaluated" really means the last expression evaluated, rather than the last line of text. For example, this subroutine returns the larger value of $fred or $barney:
  sub larger_of_fred_or_barney {
    if ($fred > $barney) {
      $fred;
    } else {
      $barney;
    }
  }

4. Arguments
 1) The parameter list (another name for the argument list) is automatically assigned to a special array variable named @_ for the duration of the subroutine.
 2) The @_ variable is local to the subroutine; if there's a global value in @_, it is saved away before the subroutine is invoked and restored to its previous value upon return from the subroutine. This also means that a subroutine can pass arguments to another subroutine without fear of losing its own @_ variable -- the nested subroutine invocation gets its own @_ in the same way. Even if the subroutine calls itself recursively, each invocation gets a new @_, so @_ is always the parameter list for the current subroutine invocation.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics