Thakur has asked for the wisdom of the Perl Monks concerning the following question:

I am confused about the behavior of the keyword 'last' in inner while loop. Suppose I have a while loop inside another while loop and I have used the keyword 'last' to come out of inner while loop. Will I exit the outer while loop too.Also can I use last for foreach loop.

Replies are listed 'Best First'.
Re: Keyword last for loops
by toolic (Bishop) on Jan 17, 2012 at 19:52 UTC
Re: Keyword last for loops
by TomDLux (Vicar) on Jan 18, 2012 at 02:19 UTC

    'last' and 'next' always break the innermost loop, so it's perfectly clear.

    But it's a lot clearer to read if you use labels ( traditionally ALLCAPS ).

    LINE: while ( my $line = <$datafile> ) { my @fields = split ',', $line; FIELD: for my $field ( @fields ) { if ( foo() ) { next FIELD; } elsif ( bar() ) { next LINE; } else { more(); } } }

    As Occam said: Entia non sunt multiplicanda praeter necessitatem.

Re: Keyword last for loops
by ikegami (Patriarch) on Jan 18, 2012 at 06:46 UTC

    It applies to for loops.

    for (1..3) { ... } for (@a) { ... } for (my $i=10; $i--; ) { ... }

    It applies to while and until loops.

    while (f()) { ... } until (f()) { ... }

    It applies to bare loops.

    { ... }

    It does NOT apply to conditional statements.

    if (f()) { ... } unless (f()) { ... }

    It does NOT apply to statement modifiers.

    ... while f(); Including: do { ... } while f(); ... for @a; ... if f(); etc

    It does NOT apply loop-like functions.

    grep { ... } @a map { ... } @a
Re: Keyword last for loops
by planetscape (Chancellor) on Jan 18, 2012 at 09:06 UTC

    Please see T.I.T.S. - it's faster even than asking PerlMonks! (And, bonus, sounds at least slightly illicit!)

    HTH,

    planetscape