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

In searching a flatfile database, can I stop a while loop when i find what I'm looking for? Does the "last" actually stop this loop?

while(<ACCOUNTS>) { my %account = split(/::/, $_); if( $account{"MASTER"} eq $_[0] ) { foreach my $key(keys(%account)) { #do something here } last; } }

Edited by Chady -- restored original contents and title.

Replies are listed 'Best First'.
Re: Can a while loop be stopped with "last"?
by rjbs (Pilgrim) on Jul 14, 2004 at 02:40 UTC
    It might have been faster to try it yourself than to type in the question:
    perl -e 'while (1) { if (1) { last } }'
    The above code does not run forever. Question answered!
    rjbs
      It might have been even faster to look up the documentation for last with perldoc -f last, or here: perlfunc. Look at the example! It's got a while loop with last breaking out of it.

      # example from perldoc -f last LINE: while (<STDIN>) { last LINE if /^$/; # exit when done with header #... }
Re: Can a while loop be stopped with "last"?
by ysth (Canon) on Jul 14, 2004 at 02:34 UTC
    Yes.

    You can even use last in a bare block:

    Loop: { # do some stuff last Loop if $done; # do some more stuff redo Loop; }
Re: Can a while loop be stopped with "last"?
by pg (Canon) on Jul 14, 2004 at 03:23 UTC

    As others said, the answer is yes. However this reminds me something interesting. do {} is not a loop structure.

    use warnings; use strict; my $i; do { print ++$i; last if ($i == 10); } until (0);

    When kyou run this code, it complaints that "Can't "last" outside a loop block at a.pl line 7.". However it still gives what you want, and prints the result "12345678910".

      You can correct that somewhat with extra curlies:  do {{ ... }} until/while ... to get next and redo to work, or  { do { ... } until/while ... } to get last to work. Unfortunately, you can't do both (without resorting to a label).
Re: Can a while loop be stopped with "last"?
by Juerd (Abbot) on Jul 14, 2004 at 08:25 UTC

    --

    Sigh.

    Q: Can I ...?
    A: TRY IT

    Q: Can I ...?
    A: I know I can. I don't know if *you* can.

    Q: Can I ...?
    A: RTFM

    Pick one.

      what is RTFM?
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Can a while loop be stopped with "last"?
by ercparker (Hermit) on Jul 14, 2004 at 02:43 UTC
    yes, last exits the innermost enclosing loop.
    this is from perldoc perlfunc(ran from the command line):

    The "last" command is like the "break" statement in C (as used
    in loops); it immediately exits the loop in question. If the
    LABEL is omitted, the command refers to the innermost enclosing
    loop. The "continue" block, if any, is not executed:
    LINE: while (<STDIN>) { last LINE if /^$/; # exit when done with header #... }