Leon
Leon

Reputation: 468

How to force Perl scripts quit when it is running in loops?

I use Perl to analyze my research data (multiple large files which may be edited or modified by users while program is running).

In my program, there are scripts to check whether the file is complete or not before it analyze the data in one of files. This check is processed in multiple loops. If I simply use "exit", it only exit a loop. How can I force the scripts to quit and generate an error message for user before it quit? In my program, there is a defined variable which be output to a log file at the end of the program. I do NOT want to use GOTO command. Any further information is highly appreciated.

    ......
foreach $dir (@dirs)
{
   ...
   $file="$dir$filename";
   $file_size=`wc -l $file`;
   $line=`grep -n TIMESTEP $file`;

   #read the first line no of each frame in a data file
   @values=split(/\r?\n/,$line);
   $loop_i=0;
   $tmp=0;   #save line no for the first frame 
   foreach $sub_line (@values)
   {
     @sub_values=split(/:/,$sub_line);
     $line_no[$loop_i]=$sub_values[0];
     #check the line number in each frame same or not, if not quit
     if($loop_i==1){$tmp=$line_no[$loop_i]-$line_no[$loop_i-1];}
     elsif($loop_i>1)
     { $_=$line_no[$loop_i]-$line_no[$loop_i-1]; 
       if($_ <> $tmp) 
       {$flag=0; $err_message="$err_message; incomplete data (each frame has different line number)"; 
       exit;   #cannot quit the whole program 
       } 
     }
     else{;}
     $loop_i++;
   }#end foreach $sub_line (@values)
   .....
}#end foreach $dir (@dirs)

....

Upvotes: 2

Views: 1084

Answers (1)

brian d foy
brian d foy

Reputation: 132832

I think what you want are loop controls. You can use next, last, or redo to break out of a loop early, stop a loop completely, or process the same iteration again. With nested loops you can use a label to specify which loop you want to control:

DIR: foreach my $dir ( ... ) {
    ...
    LINE: foreach my $line ( ... ) {
        next LINE if $skip_line;
        last LINE if ...;
        next DIR if ...;
        }
    }

Upvotes: 1

Related Questions