Learning Perl: 10.1. The unless Control Structure

Previous Page
Next Page

 

10.1. The unless Control Structure

In an if control structure, the block of code is executed only when the conditional expression is true. If you want to execute a block of code only when the conditional is false, change if to unless:

    unless ($fred =~ /^[A-Z_]/w*$/i) {
      print "The value of /$fred doesn't look like a Perl identifier name./n";
    }

Using unless says to run the block of code unless this condition is true. It's like using an if test with the opposite condition. Another way to say it is that it's like having the else clause on its own. Whenever you see an unless you don't understand, you can rewrite it (in your head or in reality) as an if test:

    if ($fred =~ /^[A-Z_]/w*$/i) {
      # Do nothing
    } else {
      print "The value of /$fred doesn't look like a Perl identifier name./n";
    }

It's no more or less efficient, and it should compile to the same internal byte codes. Another way to rewrite it would be to negate the conditional expression by using the negation operator (!):

    if ( ! ($fred =~ /^[A-Z_]/w*$/i) ) {
      print "The value of /$fred doesn't look like a Perl identifier name./n";
    }

You should pick the way of writing code that makes the most sense to you since that will probably make the most sense to your maintenance programmer. If it makes the most sense to write if with a negation, do that. More often, you'll likely find it natural to use unless.

10.1.1. The else Clause with unless

You can have an else clause with an unless. Though this syntax is supported, it can be confusing:

    unless ($mon =~ /^Feb/) {
      print "This month has at least thirty days./n";
    } else {
      print "Do you see what's going on here?/n";
    }

Some people may wish to use this, especially when the first clause is short (perhaps only one line) and the second is several lines of code. But we'd make this one a negated if or maybe swap the clauses to make a normal if:

    if ($mon =~ /^Feb/) {
      print "Do you see what's going on here?/n";
    } else {
      print "This month has at least thirty days./n";
    }

Remember you're always writing code for two readers: the computer that will run the code and the human being who has to keep the code working. If the human can't understand what you've written, pretty soon the computer won't be doing the right thing either.

Previous Page
Next Page
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值