没有包或对象引用,无法调用方法"try"

Alw*_*oss 4 perl try-catch

我在perl中有一个try catch块

try {
    //statement 1
    //statement 2
};
catch Error with
{
    print "Error\n";
}
Run Code Online (Sandbox Code Playgroud)

当我运行perl程序时,我收到以下错误

无法在没有包或对象引用的情况下调用方法"尝试"...

eph*_*ent 5

Perl不提供trycatch关键字.要捕获引发的"异常" die,您可以设置$SIG{__DIE__}处理程序或使用eval.块形式比字符串形式更受欢迎,因为解析在编译时发生一次.

eval {
    // statement 1
    // statement 2
}
if ($@) {
    warn "caught error: $@";
}
Run Code Online (Sandbox Code Playgroud)

有各种模块提供更传统try的功能,例如Try::Tiny.

  • 你错过了; 在评估结束时{...}; 声明.出于这些原因,使用Try :: Tiny通常更容易 (2认同)

Leo*_*erd 5

您可能想要一个CPAN模块,例如Try::Tiny:

use Try::Tiny;

try {
  # statement 1
  # statement 2
}
catch {
  print "Error\n";
};
Run Code Online (Sandbox Code Playgroud)