Mark Stosberg wrote:

Sometimes I use 'given' blocks to set a value. To save repeating myself
on the right hand side of the given block, I found I kept want to do this:

my $foo = given { }

...and have whatever value that was returned from when {} or default {}
populate $foo.

Isn't it still the case that the last expression evaluated within a
closure is returned by the closure?  And isn't a given block just a
fancy kind of closure?

The question is whether or not a code block can be used where the
parser expects an expression; for instance, could one say:

 my $foo = if condition {"BAR"} else {"BAZ"};

?

I'm no expert, but it occurs to me that allowing this could be a
parsing nightmare.

ISTR a programming construct along the lines of "eval" that is
effectively shorthand for "sub { ... }()".

It turns out pugs already allow this, through the trick of wrapping the
given block in an anonymoose sub...which is then immediately executed:

my $rm = sub { given $rm_param {
        when Code  { $rm_param(self)   }
        when Hash  { %rm_param<run_mode> }
        default    { self.query.param($rm_param) }
    }}();

Not only do you get implicit matching on the left side, you get implicit
return values on the right!

I'd just like to be able to clean that up a little to:

my $rm = given $rm_param {
                when Code  { $rm_param(self)   }
                when Hash  { %rm_param<run_mode> }
                default    { self.query.param($rm_param) }
    };

So what happens if you forget to include a default in the given?

--
Jonathan "Dataweaver" Lang

Reply via email to