Continue instead of 'or die' in Perl

Viewed 518

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?

4 Answers

The equivalent of C's has continue is called next in Perl.

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

You can replace die with warn. die outputs an error message and exits the script; warn outputs an error message and does not exit the script.

my $sth = $database->prepare($sql) or warn "Failed to prepare SQL";
$sth->execute() or warn "Failed to execute SQL";

Just to add one additional solution here, you could use a try-catch block (called eval in perl).

eval {
  my $sth_2 = $database->prepare($sql_2) or die "Failed to prepare SQL $DBI::errstr"; 
  $sth_2->execute(); 
};
if($@) {
  warn "Error executing $sql2 => $@";
  next;
}
Related