[Melbourne-pm] given/when

Damian Conway damian at conway.org
Mon Oct 29 23:26:05 PDT 2012


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

Sorry. Let me try again.

Normally, this:

    when (EXPR) {...}

is the same as:

    if ($_ ~~ EXPR) {...; break; }

But not in the Eight Special Cases (as listed in perlsyn).

One of those E.S.C. is when EXPR is a subroutine call:

    when (foo()) {...}

which is always equivalent to:

    if (foo()) {...; break; }


So, in your first example:

    when (true) { print "true".$/; }

is equivalent to:

    if (true()) { print "true".$/; break; }

which is the same as:

    if (1) { print "true".$/; break; }

The value 1 is true, so the first when triggers,
prints "true", and then control exits the given.

And your second example:

    when (M) { print "m".$/; }

is equivalent to:

    if (M) { print "m".$/; break; }

which is the same as:

    if ('M') { print "m".$/; break; }

The string 'M' is true, so the first when triggers,
prints "m", and then control exits the given.


Damian


More information about the Melbourne-pm mailing list