next, lastの裏芸。

うわ、こんなことできたんだ。

my $res = 0;

{
  if (scalar(@ARGV) == 0) {
    $res = 1;
    last;
  }
  
  if ($ARGV[0] == 1) {
    $res = 2;
    next;
  }
  
  $res = 3;
}

print $res . "\n";


これをtest.plとする。

$ perl test.pl
1

$ perl test.pl 1
2

$ perl test.pl foo
3


驚くことにsyntax errorにはならない。
next, lastはbreak的に使うこともできるのか!


まぁnextを使うと意味が通らないからbad practiceっぽいけど、
lastだと「無名ブロックをlast(終了する)」と読めていい感じ。