Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: while loop question

by Ovid (Cardinal)
on Sep 06, 2012 at 13:58 UTC ( #992095=note: print w/ replies, xml ) Need Help??


in reply to while loop question

Yes, but it has to be handled manually and you'll have to consider the best way of handling that. One way of handling this is retesting the condition in a continue block:

while (EXPR) BLOCK continue BLOCK

Note variables defined in the EXPR of the while loop are visible in the scope of the continue block. That's what makes this work even if you can't necessarily do this after the while loop because the condition you want to test may no longer be valid and you can't tell if a last was used or not.

use 5.10.0; my @list = qw(one two three); while ( defined( my $element = shift @list ) ) { } continue { if ( defined $element ) { say $element; } if ( !@list ) { say "We've now finished processing the while loop"; } }

And that prints out:

one two three We've now finished processing the while loop

Again, the variants of this technique change from time to time, depending on what you need. Be careful, though. Using last in the while loop will skip the continue statement, but that appears to be what you want in this case.


Comment on Re: while loop question
Select or Download Code
Re^2: while loop question
by Freezer (Sexton) on Sep 06, 2012 at 14:31 UTC
    Within this context  last does not does not skip the  continue block.
    LINE: while (<LINE_INPUT>){ print "I am here B\n"; chomp; my $entry_no_old = $entry_no_new; # a bit of a work around use +d here if ($_ =~ /^(\d{1,3})\t(\d{3,5})/){ next LINE if $1 < $start_point; print "I am here C\n"; $entry_no_new = $1; last LINE if ($entry_no_new > $entry_no_old);

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2014-09-30 22:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (385 votes), past polls