条件分支

ifelsifelse

这里没有什么特别之处,除了elsif的拼写:

  1. my $word = "antidisestablishmentarianism";
  2. my $strlen = length $word;
  3. if($strlen >= 15) {
  4. print "'", $word, "' is a very long word";
  5. } elsif(10 <= $strlen && $strlen < 15) {
  6. print "'", $word, "' is a medium-length word";
  7. } else {
  8. print "'", $word, "' is a short word";
  9. }

Perl提供了一种更简短的“statement if condition”语法,对于的语句强烈推荐这种写法:

  1. print "'", $word, "' is actually enormous" if $strlen >= 20;

unlesselse

  1. my $temperature = 20;
  2. unless($temperature > 30) {
  3. print $temperature, " degrees Celsius is not very hot";
  4. } else {
  5. print $temperature, " degrees Celsius is actually pretty hot";
  6. }

最好像避开瘟疫一样避开unless语句,因为这实在太容易把读者搞得晕头转向。“unless [… else]”语句块可以显而易见地通过对条件取反(或者保持条件不变调换语句块的位置)来重构成“if [… else]”。万幸的是,没有elsunless关键字。

而相比之下,这种写法就被强烈推荐,因为实在是太易于阅读了:

  1. print "Oh no it's too cold" unless $temperature > 15;

三目运算符

三目运算符?:使得简单的if语句可以嵌入到其他语句内。一种常规的用法就是用来处理单复数形式:

  1. my $gain = 48;
  2. print "You gained ", $gain, " ", ($gain == 1 ? "experience point" : "experience points"), "!";

题外话:单复数形式最好都写出完整的拼写,不要自作聪明地写成下面这种样子,要不然别人永远也无法在代码中查找、替换到“tooth”或者“teeth”了:

  1. my $lost = 1;
  2. print "You lost ", $lost, " t", ($lost == 1 ? "oo" : "ee"), "th!";

三目运算符可以嵌套:

  1. my $eggs = 5;
  2. print "You have ", $eggs == 0 ? "no eggs" :
  3. $eggs == 1 ? "an egg" :
  4. "some eggs";

if语句在scalar上下文中进行求值。举例说明,if(@array)当且仅当@array包含大于等于1个元素的时候返回true,而元素的内容则无关紧要(也许包括undef或者其他我们真正关心的代表false的值)。