[Melbourne-pm] given/when

Mathew Robertson mathew.blair.robertson at gmail.com
Mon Oct 29 21:37:44 PDT 2012


On 30 October 2012 13:27, Damian Conway <damian at conway.org> wrote:

> Mathew Robertson asked:
>
> > What is the expected output of this:
> > my $x = 0;
> > given ($x) {
> >   when (true) { print "true".$/; }
> >   when (false) { print "false".$/; }
> >   default { print "unknown".$/; }
> > }
>
> Expected outcome is: "true"
>
> As explained in perlsyn:
>
>       Most of the time, "when(EXPR)" is treated as an implicit smart match
> of
>        $_, i.e. "$_ ~~ EXPR". (See "Smart matching in detail" for more
>        information on smart matching.) But when EXPR is one of the below
>        exceptional cases, it is used directly as a boolean:
>
>        o   a subroutine or method call
>
> Yes, it's arguably broken and/or stupid. But it's as documented.
>
> Workaround:
>
>     my $TRUE  = 1;
>     my $FALSE = 0;
>     my $x = 0;
>     given ($x) {
>         when ($TRUE) { print "true".$/; }
>         when ($FALSE) { print "false".$/; }
>         default { print "unknown".$/; }
>     }
>
> Damian
>

I found that passage in perlsyn, but it didn't explain the behaviour, aka:
EXPR is an expression that is used as a boolean, so I assumed that it
referred to the returned value.. cf: undef is boolean-false inside "if
(...)" context and "0E0" is boolean-true inside "if (...)".

And thus is why I posted the alternative using "M" and "N"... which I
expected to be boolean-true inside the conditional.

Indeed it is was documented, but I didn't understand the *magic*... :)

cheers,
Mathew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/melbourne-pm/attachments/20121030/529b66f8/attachment.html>


More information about the Melbourne-pm mailing list