Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: VB "On Error" Equivalent in Perl

by wind (Priest)
on Nov 28, 2007 at 19:55 UTC ( [id://653647]=note: print w/replies, xml ) Need Help??


in reply to VB "On Error" Equivalent in Perl

Check out Conway's Perl Best Practices. From Chapter 13: Error Handling, Section Recoverable Failure, we find the following technique:
use Carp qw(croak); use English qw(-no_match_vars); use Net::FTP; use Time::HiRes qw(sleep); use strict; my $MAX_TRIES = 15; my $ftp; TRY: for my $try (1..$MAX_TRIES) { # If successful, we're done. eval { $ftp = Net::FTP->new("some.host.name", Debug => 0) or die "Cannot connect to some.host.name: $@"; last TRY; }; # Report non-recoverable failure if no more tries croak( $EVAL_ERROR ) if $try == $MAX_TRIES; # Try again after a nap (approximate fibonacci) sleep( rand (1.618 ** $try) ); }
- Miller

Update: Missing Semi-colon.

Replies are listed 'Best First'.
Re^2: VB "On Error" Equivalent in Perl
by erroneousBollock (Curate) on Nov 29, 2007 at 01:28 UTC
    eval { $ftp = Net::FTP->new("some.host.name", Debug => 0) or die "Cannot connect to some.host.name: $@"; last TRY; }
    I'm curious about your use of $@ om the second line of the eval. How would $@ be set without causing an exception that would throw control outside the eval?

    If the die "Cannot ..." ever occurs, wouldn't $@ be empty?

    Surely $@ is only useful outside the eval?

    Also, eval {} is a statement and should be followed by a semicolon if further statements are to follow in the current block. Your code doesn't compile.

    -David

      That is explained in the documentation for Net::FTP.
      If the constructor fails undef will be returned and an error message will be in $@.
      All other Net::FTP methods save their error message in $ftp->message.

      I've also sometimes wondered about the logic of this. Nevertheless, that's the way it is.

      - Miller

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://653647]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (1)
As of 2024-04-25 04:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found