Note of Learning Perl--Subroutines

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值