Learning Perl: 4.1. Defining a Subroutine

Previous Page
Next Page

 

4.1. Defining a Subroutine

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

[] Okay, purists, we admit that 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 such as 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 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.[*] Subroutine definitions are global; without some powerful trickiness, there are no private subroutines.[] If you have two subroutine definitions with the same name, the second one overwrites the first one.[] That's generally considered bad form or the sign of a confused maintenance programmer.

[*] 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 perlsub manpage for more information.

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

[] 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 you'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. You'll see how to make private variables in the section "Private Variables in Subroutines" later in this chapter.

Previous Page
Next Page
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值