Learning Perl: 10.5. The elsif Clause

Previous Page
Next Page

 

10.5. The elsif Clause

Every so often, you may need to check a number of conditional expressions, one after another, to see which one of them is true. This can be done with the if control structure's elsif clause, as in this example:

    if ( ! defined $dino) {
      print "The value is undef./n";
    } elsif ($dino =~ /^-?/d+/.?$/) {
      print "The value is an integer./n";
    } elsif ($dino =~ /^-?/d*/./d+$/) {
      print "The value is a _simple_ floating-point number./n";
    } elsif ($dino eq '') {
      print "The value is the empty string./n";
    } else {
      print "The value is the string '$dino'./n";
    }

Perl will test the conditional expressions one after another. When one succeeds, the corresponding block of code is executed, the whole control structure is done,[*] and the execution goes on to the rest of the program. If none has succeeded, the else block at the end is executed. (The else clause is optional, though in this case it's often a good idea to include it.)

[*] There's no "fall-through" to the next block as in the "switch" structure of languages such as C.

There's no limit to the number of elsif clauses, but Perl has to evaluate the first 99 tests before it can get to the hundredth. If you'll have more than half a dozen elsifs, you should consider whether there's a more efficient way to write it. The Perl FAQ (see the perlfaq manpage) has a number of suggestions for emulating the "case" or "switch" statements of other languages.

You may have noticed by this point that the keyword is spelled elsif, with one e. If you write it as "elseif," with a second e, Perl will tell you that it is the incorrect spelling. Why? Because Larry says so.[*]

[*] In fact, he resists any suggestion that it even be permitted as a valid alternative spelling: "If you want to spell it with a second e, it's simple. Step 1: Make up your own language. Step 2: Make it popular." When you make your own programming language, you can spell the keywords any way you'd like. We hope you will decide that yours shouldn't be the first to have an "elseunless."

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值