Perl-last-statement

提供:Dev Guides
移動先:案内検索

Perlの最後のステートメント

ループ内で last ステートメントが検出されると、ループは直ちに終了し、プログラム制御はループに続く次のステートメントから再開します。 LABELがループのラベルである最後のステートメントでLABELを提供できます。 last ステートメントは、LABELが指定されていない場合に最も近いループに適用されるネストされたループ内で使用できます。

ループ上に continue ブロックがある場合、実行されません。 別の章にcontinueステートメントが表示されます。

構文

Perlの last ステートメントの構文は-

last [LABEL];

流れ図

Perl last statement

例1

#!/usr/local/bin/perl

$a = 10;
while( $a < 20 ) {
   if( $a == 15) {
      # terminate the loop.
      $a = $a + 1;
      last;
   }
   print "value of a: $a\n";
   $a = $a + 1;
}

上記のコードが実行されると、次の結果が生成されます-

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14

例2

私たちは次のステートメントと一緒にLABELを使用しようとしている一例を見てみましょう-

#!/usr/local/bin/perl

$a = 0;
OUTER: while( $a < 4 ) {
   $b = 0;
   print "value of a: $a\n";
   INNER:while ( $b < 4) {
      if( $a == 2) {
         # terminate outer loop
         last OUTER;
      }
      $b = $b + 1;
      print "Value of b : $b\n";
   }
   print "\n";
   $a = $a + 1;
}

上記のコードが実行されると、次の結果が生成されます-

value of a : 0
Value of b : 1
Value of b : 2
Value of b : 3
Value of b : 4

value of a : 1
Value of b : 1
Value of b : 2
Value of b : 3
Value of b : 4

value of a : 2