Question

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,

Was it helpful?

Solution

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" );

}

OTHER TIPS

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

I'm having a hard time understanding why this needs to be wrapped up in a do. Is there a reason that this isn't sufficient?

my $ftp_ok = $ftp->put( $my_file )
  or log("Couldn't upload $my_file" ) and return -1;

log("$my_file uploaded") if $ftp_ok;

This assumes that the put function doesn't always return undef on success.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top