Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^2: Perl try { } catch(e) { }

by Superfox il Volpone (Sexton)
on Mar 03, 2015 at 15:18 UTC ( [id://1118614]=note: print w/replies, xml ) Need Help??


in reply to Re: Perl try { } catch(e) { }
in thread Perl try { } catch(e) { }

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

Replies are listed 'Best First'.
Re^3: Perl try { } catch(e) { }
by Anonymous Monk on Mar 03, 2015 at 15:29 UTC

    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 $@!

Re^3: Perl try { } catch(e) { }
by karlgoethebier (Abbot) on Mar 03, 2015 at 17:39 UTC
    "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»

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2024-09-09 09:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.