Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 629
Rob Wells Avatar asked Mar 20 '09 16:03

Rob Wells


3 Answers

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

}

like image 154
Axeman Avatar answered Nov 06 '22 19:11

Axeman


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);
like image 45
jj33 Avatar answered Nov 06 '22 17:11

jj33


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";
};
like image 1
Geo Avatar answered Nov 06 '22 17:11

Geo