betmatt has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I have been trying to understand something of what python has to offer.
try: # Runs first <code> except: # Runs if exception occurs in try block <code> else: # Executes if try block *succeeds* <code> finally: # This code *always* executes <code>
Does anyone here have experience of converting one to another. Python to Perl or visa versa. I would be interested in seeing examples of how these statements would translate between the two languages.

Replies are listed 'Best First'.
Re: Exception clauses
by Discipulus (Abbot) on Jun 06, 2019 at 09:37 UTC
    Hello betmatt

    you can use Try::Tiny or Syntax::Keyword::Try module. From the synopis of the modules:

    use Try::Tiny; # handle errors with a catch handler try { die "foo"; } catch { warn "caught error: $_"; # not $@ }; # or use Syntax::Keyword::Try; sub foo { try { attempt_a_thing(); return "success"; } catch { warn "It failed - $@"; return "failure"; } }

    Also look at ModernPerl book in the chapter dedicated to Exceptions.


    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

      Discipulus just to add that there exists a finally clause for both modules you mentioned. Here is how to do it with Try::Tiny:

      try { try_some_code() } catch { warn "oops: $_" } finally { $x = 'always-executes' };

      btw, I was bitten many times by forgetting the last colon and getting all sort of misleading error messages. This is not java!

Re: Exception clauses
by holli (Abbot) on Jun 06, 2019 at 17:09 UTC
    Note that even though neither of the aforementioned modules supports an else-block you can simulate one. Both modules allow to return a value from the try-block. Try::Tiny returns true/false by itself, Syntax::Keyword::Try returns whatever the try-block returns (on success). Basically
    my $success = try { # Runs first 1; } catch { # Runs if exception occurs in try block } finally { # This code *always* executes }; if ( $success ) { # Executes if try block *succeeds* }


    You can lead your users to water, but alas, you cannot drown them.