Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking out of a 'do while' loop in Perl

Tags:

perl

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?

like image 648
user3606175 Avatar asked Sep 11 '14 19:09

user3606175


Video Answer


1 Answers

Do not use the statement modifier form of do:

do BLOCK does not count as a loop, so the loop control statements next, last, or redo cannot be used to leave or restart the block. See perlsyn 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;
}
like image 142
Miller Avatar answered Sep 19 '22 15:09

Miller