Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: A few random questions from Learning Perl 3

by pg (Canon)
on Jan 06, 2003 at 05:52 UTC ( #224556=note: print w/replies, xml ) Need Help??


in reply to A few random questions from Learning Perl 3

For the completeness of the "next" topic, we have to introduce the two brothers of "next": "last" and "redo".

  1. next

    The "next" statement allows you to jump to the next iteration of the loop without executing the remaining statements of the current iteration.
    foreach (1..10) { next if ($_ == 9); print("$_ "); }
    Here's what it looks like:

    1 2 3 4 5 6 7 8 10

    As you can see, 9 is missing - this is because when the value of $_ hits 9, Perl uses the "next" statement to skip to the next iteration of the loop, and so 9 never gets printed.

  2. last

    The "last" statement is used to exit the loop completely.
    foreach (1..10) { last if ($_ == 9); print("$_ "); }
    And here's the output:

    1 2 3 4 5 6 7 8

  3. redo

    And finally, the redo statement lets you restart a particular iteration of the loop:
    foreach (1..10) { print("$_ "); if ($_ == 9 && $flag != 1) { $flag=1; redo; } }
    In this case, here's what you'll see:

    1 2 3 4 5 6 7 8 9 9 10

Replies are listed 'Best First'.
Re: Re: A few random questions from Learning Perl 3
by talexb (Canon) on Jan 06, 2003 at 14:39 UTC

    Excellent answer, with one small adjustment to the last example to do with redo ..

    my $flag = 0; foreach (1..10) { print("$_ "); if ($_ == 9 && $flag != 1) { $flag=1; redo; } }

    I have initialized flag to zero at the beginning of the loop. This was, of course, understood :) by all readers, but for the newcomer, it might be helpful.

    --t. alex
    Life is short: get busy!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://224556]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2020-02-23 07:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What numbers are you going to focus on primarily in 2020?










    Results (102 votes). Check out past polls.

    Notices?