继续代替Perl中的 "or die"。

问题描述 投票:0回答:1

我的Perl脚本中有一个循环,准备并执行一条SQL语句,就像这样。

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(); 
} 

据我所知,die会导致代码的执行停止。能否继续下一个循环,而不是停止整个脚本的执行?例如,是否可以做这样的事情。

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

"or next "可以吗?

loops perl syntax continue die
1个回答
5
投票

相当于C语言的有 continue 叫做 next 在Perl中。

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

3
投票

你可以用 diewarn. die 输出一个错误信息并退出脚本。warn 输出一个错误信息,并且不退出脚本。

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

2
投票

在这里增加一个额外的解决方案,你可以使用try-catch块(在perl中称为eval)。

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;
}

0
投票

你可以尝试使用 next 函数。https:/perldoc.perl.orgfunctionsnext.html。

© www.soinside.com 2019 - 2024. All rights reserved.