Perlにcontinue文は存在しない代わりにnext文がある
繰り返し処理の際に、特定の条件の場合出力しないとするにはcontinue文を思いつく方が多いと思います。
ただし、Perlにはcontinueブロックは存在するが、continue文というのは存在せず、代替としてnext文が存在します。
// 条件分が再評価される直前に実行 while (条件) { ... } continue { ... }
my $i = 0;
while ($i <= 5) {
print "$i";
$i++;
} continue {
print "\n";
}
// 実行結果
0
1
2
3
4
5
上記の例では、条件が再評価される前に改行コードを出力する処理をしています
continue文がない代わりにnext文が存在します。
「next文」を使用すれば、特定の条件の際に処理をスキップすることができます。
my $i = 0;
while ($i < 5) {
$i++;
if ($i == 3){
next;
}
print "$i\n";
}
// 実行結果
1
2
4
5
特定の条件(※上記では$i == 3のとき処理がスキップされる)のが確認できました。
ちなみにcontinue文は存在しないためエラーとなります。
my $i = 0;
while ($i < 5) {
$i++;
if ($i == 3){
continue;
}
print "$i\n";
}
// 実行結果
1
2
Can't "continue" outside a when block at TEST.pl line 5.







コメントを残す