[Melbourne-pm] Using given/when to return values

David Warring david.warring at gmail.com
Thu Jun 10 20:08:08 PDT 2010


Hi Toby,

I had a look at the latest perl 5.13.1. Someone's just fixed it!

>From  perl5131delta.pod:

   "given" return values
       Starting from this release, "given" blocks returns the last evaluated
       expression, or an empty list if the block was exited by "break". Thus
       you can now write:

           my $type = do {
            given ($num) {
             break     when undef;
             'integer' when /^[+-]?[0-9]+$/;
             'float'   when /^[+-]?[0-9]+(?:\.[0-9]+)?$/;
             'unknown';
            }
           };

       See "Return value" in perlsyn for details.

Cheers
- David

On Thu, Jun 3, 2010 at 8:17 AM, David Warring <david.warring at gmail.com>wrote:

> Toby,
>
> I've noticed this. It's supposed to be a back-port of a Perl 6 feature.
>
> I grokked the Perl 6 test suite and fond the following
> in t/spec/S04-statements/given.t
>
> ==================================
>     # from apocalypse 4
>     #?rakudo skip 'parsefail on each(... ; ...)'
>     {
> # simple example L<S04/"Switch statements" /You don't have to use an
> explicit default/>
>  for each(("T", "E", 5) ; (10, 11, 5)) -> $digit, $expected {
>     my $result_a = do given $digit {
>  when "T" { 10 }
> when "E" { 11 }
> $digit
>     };
>
>     my $result_b = do given $digit {
> when "T" { 10 }
>  when "E" { 11 }
> default  { $digit }
>     };
>
>     is($result_a, $expected, "result of $digit using implicit default {} is
> $expected");
>     is($result_b, $expected, "result of $digit using explicit default {} is
> $expected");
>  }
>     }
> ===================================
>
> So it looks as if this is inconsistently implemented across Perl 6 & 5.
>
> I would've thought that Perl 5 should behave the same way. Also it wouldn't
> hurt to back-port the 'given' tests from rakudo.
> - David
>
> On Wed, Jun 2, 2010 at 3:16 PM, Toby Corkindale <
> toby.corkindale at strategicdata.com.au> wrote:
>
>> An annoyance right now is that the given/when syntax does not return the
>> values in the code block executed, so you can't use them inside grep,etc.
>>
>> Has anyone else noticed a way around that? (Apart from wrapping it in an
>> anonymous subroutine and then returing out of the when blocks)
>> _______________________________________________
>> Melbourne-pm mailing list
>> Melbourne-pm at pm.org
>> http://mail.pm.org/mailman/listinfo/melbourne-pm
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/melbourne-pm/attachments/20100611/b164a3b3/attachment.html>


More information about the Melbourne-pm mailing list