Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continue instead of 'or die' in Perl

Tags:

loops

perl

I have a loop in my Perl script that prepares and executes a SQL statement, like this:

my $sql_1 = select * from TABLE; 
my $sth_1 = $database->prepare($sql_1) or die "Failed to prepare SQL"; 
$sth_1->execute() or die "Failed to execute SQL"; 
my $results = sth_1-> fetchall_arrayref({}); 

my params_ins; 
my params_del; 

foreach my $row($results) { 
  params_ins = $row->{params_ins} 
  params_del = $row->{params_del} 

  my $sql_2 = 
    begin transaction 
      exec delete_sp(params_ins) 
      exec insert_sp(params_del) 
    end transaction 

  my $sth_2 = $database->prepare($sql_2) or die "Failed to prepare SQL"; 
  $sth_2->execute(); 
} 

As I understand, die will cause the execution of the code to stop. Would it be possible to continue to the next loop instead of stopping the whole execution of the script? For example, would it be possible to do something like:

  my $sth_2 = $database->prepare($sql_2) or continue; 
  $sth_2->execute(); 

Would 'or next' work?

like image 466
Keybladerhuy Avatar asked Oct 24 '25 00:10

Keybladerhuy


1 Answers

The equivalent of C's continue is called next in Perl (and the equivalent of break in loops is last).

my $sth_2 = $database->prepare( $sql_2 )
   or do {
      warn( "Failed to prepare SQL: $DBI::errstr" );
      next;
   };

or

my $sth_2 = $database->prepare( $sql_2 );
if ( !$sth_2 ) {
   warn( "Failed to prepare SQL: $DBI::errstr" );
   next;
}
like image 122
ikegami Avatar answered Oct 26 '25 19:10

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!