I have a 'do while' loop in Perl, and I need to break out if in the middle. I see last label;
is how I break out of loop, but I can't figure out where to add label. Here is my sample code.
my $count = 5;
do {
print $count;
if ( $count == 2 ) { last TAG; }
$count--;
} while ( $count > 0 );
TAG: print "out";
The above fails with "cannot find label". What am I doing wrong?
Do not use the statement modifier form of do
:
do
BLOCK
does not count as a loop, so the loop control statementsnext
,last
, orredo
cannot be used to leave or restart the block. Seeperlsyn
for alternative strategies.
Instead, I recommend using a while
loop.
my $count = 5;
while ( $count > 0 ) {
print $count;
last if $count == 2;
$count--;
}
print "out";
Outputs:
5432out
If you need a construct that will always run one time before testing a condition, then use a while
loop of this form:
while (1) {
...
last if COND;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With