tags:

views:

614

answers:

5

In reading about Perl 6, I see a feature being trumpeted about, where you no longer have to do:

return "0 but true";

...but can instead do:

return 0 but True;

If that's the case, how does truth work in Perl 6? In Perl 5, it was pretty simple: 0, "", and undef are false, everything else is true.

What are the rules in Perl 6 when it comes to boolean context?

+7  A: 

According to O'Reilly's Perl 6 and Parrot Essentials, false is 0, undef, the empty string, and values flagged as false. true is everything else.

Also, Perl 6 has both a primitive boolean type and by having True and False roles that any value can mix in (so you can have a "0 but True" value or a "1 but False" one for example, or a false list containing elements, or a true list that's empty).

See http://www.mail-archive.com/[email protected]/msg09930.html

Mark Cidade
That book is ancient and does not represent the current state of the language.
brian d foy
+10  A: 

See Synopsis 12: Roles.

The rules are the same, but the "but" copies the 0 and applies a role to the copy that causes it to be true in boolean context.

You can do the same thing with overload in Perl 5.

ysth
Er, don't you mean "true in a boolean context"?
Ovid
+11  A: 

Perl 6 evaluates truth now by asking the object a question instead of looking at it's value. The value is not the object. It's something I've liked about other object languages and will be glad to have in Perl: I get to decide how the object responds and can mutate that. As ysth said, you could do that in Perl 5 with overload, but I always feel like I have to wash my hands after doing it that way. :)

If you don't do anything to change that, Perl 6 behaves in the same way as Perl 5 so you get the least amount of surprise.

brian d foy
+7  A: 

Truthness test just calls the .true method on an object, so the "mix in" operation $stuff but True just (among other things) overrides that method.

This is specified in S02, generally enum types (of which Bool is one) are described in S12.

moritz
+2  A: 

So to combine what I think to be the best of everyone's answers:

When you evaluate a variable in boolean context, its .true() method gets called. The default .true() method used by an object does a Perl 5-style <0, "", undef> check of the object's value, but when you say "but True" or "but False", this method is overridden with one that doesn't look at the value just returns a constant.

One could conceivable write a true() method which, say, returned true when the value was even and false when it was odd.

raldi