Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: What could be the exact usage of While - continue loop

by naikonta (Curate)
on May 09, 2007 at 04:18 UTC ( [id://614293]=note: print w/replies, xml ) Need Help??


in reply to What could be the exact usage of While - continue loop

The continue block is guaranteed to be executed in each iteration.
my $i = my $j = 0; while ($i++ < 5) { next if $i == 2 || $i == 4; print "i:$i\n"; } continue { $j++; printf "j:$j\n"; }
See that the i line is not always printed because it depends on if checking, while j line is always printed regardless what happens inside the while block*. This won't happen if printing j line is put inside the block as i.

But frankly, I never use continue myself in practical. It exists for some reason regarding the for loop (see Programming Perl). From the doc:

"last", "next", or "redo" may appear within a "continue" block. "last" and "redo" will behave as if they had been executed within the main block. So will "next", but since it will execute a "continue" block, it may be more entertaining.
Some monk commented on that emphasized text but I can't recall the node.

* Unless redo take place, as shown by GrandFather below. The same thing with last. Consider,

my $yodda = 0; while ($yodda < 6) { last if $yodda == 5; redo if ++$yodda & 1; print "Even is "; } continue { print "$yodda\n"; }

Update: added note following correction by GrandFather

Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!

Replies are listed 'Best First'.
Re^2: What could be the exact usage of While - continue loop
by GrandFather (Saint) on May 09, 2007 at 04:37 UTC

    Actually the continue block is not executed for a redo. Consider:

    use warnings; use strict; my $yodda = 0; while ($yodda < 4) { redo if ++$yodda & 1; print "Even is "; } continue { print "$yodda\n"; }

    Prints:

    Even is 2 Even is 4

    DWIM is Perl's answer to Gödel
      Well, you hit me at the "regardless" part then :-)

      Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (2)
As of 2024-04-20 03:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found