[Melbourne-pm] given/when
Damian Conway
damian at conway.org
Mon Oct 29 19:27:28 PDT 2012
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
More information about the Melbourne-pm
mailing list