Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re^2: Yet more Try::Tiny problelms

by dd-b (Monk)
on May 19, 2013 at 15:10 UTC ( [id://1034224] : note . print w/replies, xml ) Need Help??


in reply to Re: Yet more Try::Tiny problelms
in thread Yet more Try::Tiny problelms

And, bingo!

#! /usr/bin/perl use feature qw (switch); use Try::Tiny; my $uv; given (17) { when (3) { print "three\n"; }; when (17) { try { print "In try block\n"; die( "Substitute undefined variable $uv\n"); print "Still in try block\n"; } catch { print "We caught $_\n"; }; } }

Output is:

$ ./t4.pl 
In try block
We caught 17

It was indeed an interaction between Try::Tiny and the switch feature. Might not happen in later versions of Perl, according to what I've read, but we're running 5.10, where it does.

Replies are listed 'Best First'.
Re^3: Yet more Try::Tiny problelms
by tobyink (Canon) on May 19, 2013 at 17:55 UTC

    It works more sanely in Perl 5.18...

    In try block We caught Substitute undefined variable

    For Perl 5.10-5.16, the easiest fix is:

    catch { our $_; # stop lexical $_ from masking global $_ print "We caught $_\n"; }
    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
      Or use "for" instead of "given" to kick things off.
Re^3: Yet more Try::Tiny problelms
by Anonymous Monk on May 19, 2013 at 17:43 UTC

    :) happens in v5.16.1 also, but if you search Try::Tiny for $_ this caveat is described but real solution is not

    I found this thread I participated in Lexical $_ in given/when vs. BLOCK arguments which had the real solution, because I ran into similar nonsense before :)

    #!/usr/bin/perl -- use feature qw (switch); use Try::Tiny; my $uv; given (17) { when (3) { print "three\n"; }; when (17) { #~ local $_; # grr Can't localize lexical variable $_ #~ my $_; ## doesn't help, Try::Tiny code is using global $_ #~ local *_; ## doesn't help , here $_ refers to lexical $_ our $_; # THIS HELPS try { print "In try block\n"; die( "Substitute undefined variable $uv\n"); print "Still in try block\n"; } catch { print "We caught global \$@ = $@\n"; print "We caught lexical \$_ = $_\n"; print "We caught global \$::_ = $::_\n"; print "We caught global \$_[0] = $_[0]\n"; }; } } __END__ In try block We caught global $@ = We caught lexical $_ = Substitute undefined variable We caught global $::_ = Substitute undefined variable We caught global $_[0] = Substitute undefined variable

    So summary, local $_ should NOT die but work just like our $_ inside given/when

    Try::Tiny documentation should lead with $::_

    I still don't think in terms of given/when -- well I do, but I spell it if/else/unless :D