Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

perl "continue" statement? 1

Status
Not open for further replies.

nfaber

Technical User
Oct 22, 2001
446
US
Hello again all,

I have this code snippet that does not work:

Code:
foreach $rpt_month (@month) {

if ($close_month == $rpt_month) {
    $close_cnt++;
    continue;
}else{
    next;
}
if ($open_month == $rpt_month) {
    $open_cnt++;
    continue;
}else{
    next;
}

what I am trying to do is if $open_month equals $rpt_month, increment a counter and continue on with the foreach loop, if not (else) skip the record and start the foreach loop again (I hope I explained that right).

Any help is appriciated,

Nick
 
Code:
foreach $rpt_month (@month) {
    next unless $close_month == $rpt_month;
    $close_cnt++;

    next unless $open_month == $rpt_month;
    $open_cnt++;
}
Perl's continue is not like C's. continue is used to set up a continue block, typically at the bottom of the loop. Next's skip to the continue block. Eventually, everyone gets there except last's. See perldoc -f continue.
Example:
Code:
print "Enter a number: ";
while (my $n = <STDIN>) {
    chomp $n;
    unless ($n =~ /^\d+$/) {
        warn qq(Must be a positive integer.\n);
        next;  # goes to [b]continue block[/b]
    }
    # do something with [b]$n[/b] here ...
    # ...
} continue {
    # everyone gets here eventually
    print "Enter a number: ";
}
HTH


 
Hmm, this is better.
Code:
print "Enter a number: ";
chomp(my $n = <STDIN>);
while ($n) {
    unless ($n =~ /^\d+$/) {
        warn qq(Must be a positive integer.\n);
        next;  # goes to continue block
    }
    # do something with $n here ...
    # ...
} continue {
    # everyone gets here eventually
    print "Enter a number: ";
    chomp($n = <STDIN>);
}
 
Isn't there a problem with using 'next' at all in the example that nfaber provided?

If $rpt_month is not equal to close_month go to the next month - it will never get to the point where you increment $open_cnt (unless the open_month and close_month happen to be the same.)

Maybe something like this:

Code:
foreach my $rpt_month (@month) {
    $close_cnt++ if ($close_month == $rpt_month);
    $open_cnt++ if ($open_month	== $rpt_month);
}
 
You're right, rharsh, that is what would happen. That seemed to be the intention expressed by the original code. My translation was intended to duplicate the intention of the original without the erroneous use of continue. The original code may in fact have logic problems as well as syntactic ones. I wasn't looking to correct those. (OK, and I'll admit I didn't notice, either, 'til you pointed it out.)

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top