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

Hi monks, I am a little confused by now to exit a loop.
while (<FH>) { ($col1, $col2) = split m/\s+/; for $file (keys %files) { if (exists $files{$file}{$col2} ) { .....do something.... } } }
All the files have been sorted, therefore, looping through file.1 file.2 etc. However, if the 'if' statement is run i need to exit the for loop and go to the next while loop entry. e.g. if the 'if' loop is executed on file.2 go to next while step and try again with file.1 I am not sure how to exit the for loop? Thanks

Replies are listed 'Best First'.
Re: exit a loop
by grep (Monsignor) on Nov 09, 2006 at 16:21 UTC
    read next and last.
    You should get code similar to this:
    #UNTESTED use strict; use warnings; my %files = ( FOO => { A => 2 }, BAR => { B => 3 } ); MAIN: while (<FH>) { my ($col1, $col2) = split m/\s+/; foreach my $file (keys %files) { if (exists $files{$file}{$col2} ) { #do something; next MAIN; } } }

    Also please use strict; and use warnings; you'll save yourself a lot of grief.

    UPDATE:

    Although it might be even cleaner (clearer and more maintainable) by creating a sub.

    ##ALSO UNTESTED while (<FH>) { my ($col1, $col2) = split m/\s+/; stuff_i_need_do($col1) if ( check_for_condition(\%files,$col2) ); } sub check_for_condition { my $files = shift || return undef; my $col = shift || return undef; foreach my $file ( keys %{$files} ) { return 1 if (exists $files{$file}{$col2} ); } return undef; } sub stuff_i_need_to_do { my $stuff = shift; #do something; }


    grep
    One dead unjugged rabbit fish later
      i think thats doing the job. Thanks for your help
Re: exit a loop
by davorg (Chancellor) on Nov 09, 2006 at 16:18 UTC

    Sounds like you want last. But it's also worth reading up on next and redo.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: exit a loop
by Melly (Chaplain) on Nov 09, 2006 at 16:19 UTC

    If I understand what you are asking, and your code, a simple "last" should do the trick (since your "for" loop is the innermost enclosing loop).

    If a bare "last" doesn't meet your needs, you can check the documentation on labels (which allow you to apply a "last" to a specific loop).

    Tom Melly, tom@tomandlu.co.uk