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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

? on subs

Status
Not open for further replies.

Porshe

Programmer
Jun 5, 2001
38
0
0
US
Hi! I have a main program that has a big foreach ($ip) loop. In this loop it calls many subroutines. When it goes into a subroutine, how can I get it to go back to the start of the foreach loop? I've tried next and return, but I don't want it to exit out of the main program.

sub ShowError {
print "Error\n";
print "Exiting\n";
#next;
}


Thanks,
Porshe
 
not the best way of coding ...but here it is:

foreach {
POINTER:
...
...
}

sub sth {
...
next POINTER;
}
 
You need to add a label to the next statement. The example below shows one way to do this.
Code:
LOOP:
foreach $ip (@list) {
    if (some error) {
         ShowError;
    }
}
sub ShowError {
   print "Error\n";
   print "Exiting\n";
   next LOOP;
}
A better way to do this would be to do it in the foreach loop. Note that the label is not needed since the next is going to the next iteration of the innermost enclosing loop.
Code:
foreach $ip (@list) {
    if (some error) {
         ShowError;
         next;
    }
}
sub ShowError {
   print "Error\n";
   print "Exiting\n";
}
 
I agree with the above. Instead of controlling the logic flow of the foreach loop from the subroutine, you should have the subroutine return a value (i.e. 1 for true, 0 for false) and use that value within the loop to control the flow. Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top