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

hi I obviously read the wrong books because I'm not able to find out how this "construct" is called:
MAIN_LOOP: for my $number_to_check (3 .. 200) { ...
So my questions about MAIN_LOOP:
- how do you call 'that'?
- how does it work?
- what do you think about its usage? (none of the books I read use it, but I've seen other code that use it often)

thanks
ben

Replies are listed 'Best First'.
Re: How Do I Use Labels?
by ikegami (Patriarch) on Sep 13, 2008 at 23:49 UTC
Re: How Do I Use Labels?
by GrandFather (Saint) on Sep 14, 2008 at 00:04 UTC

    MAIN_LOOP: is a label and is the target of constructs like next MAIN_LOOP; and last MAIN_LOOP;. However, unless you have nested loops and need "next" or "last" to apply to the outer loop, labels very seldom need to be used. Consider:

    use strict; use warnings; MAIN_LOOP: for my $number_to_check (1 .. 20) { for my $colour ('red', 'green', 'black') { next MAIN_LOOP if $number_to_check % 3 and $colour eq 'green'; print "$colour-$number_to_check "; } print "\n"; }

    prints:

    red-1 red-2 red-3 green-3 black-3 red-4 red-5 red-6 green-6 black-6 red-7 red-8 red-9 green-9 black-9 red-10 red-11 red-12 green-12 black-12 red-13 red-14 red-15 green-15 black-15 red-16 red-17 red-18 green-18 black-18 red-19 red-20

    Perl reduces RSI - it saves typing
      thank you all for your help!
Re: How Do I Use Labels?
by Perlbotics (Archbishop) on Sep 13, 2008 at 23:48 UTC
    It's called a label and among other things it can be used for loop control. perlsyn describes its details.
    Update: It can help to structure complicated nested loops, but it's better avoided in combination with goto.