Rob Wells Rob Wells - 3 months ago 10
Perl Question

How do I use a block as an 'or' clause instead of a simple die?

I want to check the results of an operation in the Net::FTP Perl module rather than die.

Typically you would do:

$ftp->put($my_file)
or die "Couldn't upload file";


But I want to do something else instead of just dying in this script so I tried:

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

log("$my_file uploaded");


But Perl complains of compilation errors saying:

syntax error at toto.pl line nnn, near "log"


which is the second log in my code fragment.

Any suggestions greatly appreciated.

cheers,

Answer

do is what you're looking for:

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

log("$my_file uploaded");

But this is probably better style:

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

If you just want to return an error condition, then you can die and use eval in the calling 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();
}

and then call

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

}