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,
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" );
}
or do{}; always makes my head hurt. Is there a good reason to use "or" syntax (which I admit using a lot for one liners) vs "if" (which I prefer for multi liners)?
So, is there a reason to use or not use one of these methods in preference of the other?
foo()
or do {
log($error);
return($error);
};
log($success);
if (!foo()) {
log($error);
return($error);
}
log($success);
use do.
here is small code snippet:
sub test {
my $val = shift;
if($val != 2) {
return undef;
}
return 1;
}
test(3) || do {
print "another value was sent";
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With