如何使用块作为'或'子句而不是简单的模具?

Rob*_*lls 14 syntax perl codeblocks

我想检查Net :: FTP Perl模块中的操作结果而不是死.

通常你会这样做:

$ftp->put($my_file)
  or die "Couldn't upload file";
Run Code Online (Sandbox Code Playgroud)

但是我想做其他事情,而不是仅仅死在这个脚本中,所以我尝试了:

$ftp->put($my_file)
  or {
      log("Couldn't upload $my_file");
      return(-1);
  }

log("$my_file uploaded");
Run Code Online (Sandbox Code Playgroud)

但是Perl抱怨编译错误说:

syntax error at toto.pl line nnn, near "log"
Run Code Online (Sandbox Code Playgroud)

这是我的代码片段中的第二个日志.

任何建议都非常感谢.

干杯,

Axe*_*man 30

do 正是你要找的:

$ftp->put($my_file)
  or do {
      log("Couldn't upload $my_file");
      return(-1);
  };

log("$my_file uploaded");
Run Code Online (Sandbox Code Playgroud)

但是,可能是更好的风格:

unless( $ftp->put( $my_file )) { # OR if ( !$ftp->put...
      log("Couldn't upload $my_file");
      return(-1);
}
Run Code Online (Sandbox Code Playgroud)

如果你只是想返回错误条件,那么你就可以die和使用eval在调用FUNC.

use English qw<$EVAL_ERROR>; # Thus, $@ <-> $EVAL_ERROR

eval { 
    put_a_file( $ftp, $file_name );
    handle_file_put();
};

if ( $EVAL_ERROR ) { 
    log( $EVAL_ERROR );
    handle_file_not_put();
}
Run Code Online (Sandbox Code Playgroud)

然后打电话

sub put_a_file { 
    my ( $ftp, $my_file ) = @_;
    $ftp->put( $my_file ) or die "Couldn't upload $my_file!";
    log( "$my_file uploaded" );
Run Code Online (Sandbox Code Playgroud)

}