in reply to Perl try { } catch(e) { }

Have you looked at how Try::Tiny does its thing. Most likely, you can reuse that code for your implementation.

Note that catch(e) is invalid syntax in Perl (unless you declare a parameterless function e()). Resorting to something like catch  my $e { is not allowed by Perl syntax either, because the & prototype works its syntactical magic only when it is the first prototype character.

You could use something like

catch { my $e= $@; ... }

... if you really want to rename $@.

Replies are listed 'Best First'.
Re^2: Perl try { } catch(e) { }
by Superfox il Volpone (Sexton) on Mar 03, 2015 at 15:18 UTC
    Aaaaahh I think I understood now how this is supposed to work:
    #!/usr/bin/env perl sub try(&$) { my ($try, $catch) = @_; eval { # perl try &$try }; if($@){ # perl catch &$catch($@); } } sub catch(&){ shift } try{ die("Frankie"); } catch { my $e = shift; print("Hello world $e\n"); }
    catch { ... } is invoked before the block in the try { ...}, and all it does is to return the block as a reference to the anonymous function defined by the catch block.
    Tricky mechanism.

    Thanks,
    s.fox

      If you're going to use that code instead of Try::Tiny (which by the way is pure Perl and has no non-core dependencies), make sure you read the "Background" section of Try::Tiny's docs, as there are a number of issues with $@!

      "Aaaaahh I think I understood ..."

      I don't (for the moment) - but i don't care about and just do:

      #!/usr/bin/env perl use strict; use warnings; use Try::Tiny; try { die qq(Goodbye World!); } catch { warn $_; }; __END__

      Best regards, Karl

      «The Crux of the Biscuit is the Apostrophe»

        There is a full implementation of try-catch block using perl filters: Nice::Try So you can do something like embedded try-catch block, return, variable assignments, catching class exception, etc. There is no need for semicolon on the lack brace.
        use Nice::Try; try { # do something die( "Argh...\n" ); } catch( $wow ) { return( $self->error( "Caught an error: $wow" ) ); } finally { # do some cleanup }
        Full disclosure: I am the author of this module that I created when Devel::Declare on which TryCatch was relying became obsolete.

        See also

        «The Crux of the Biscuit is the Apostrophe»