Name

Yet Another Perl 6 Operator: Coercion Operators

Version

Maintainer: Adriano Ferreira <ferreira@cpan.org>
Date: 21 Sep 2007
Last Modified: 25 Sep 2007
Number: 4
Version: 5
Status: Published

Body

In Perl 5, we expect values to DWIM ("do what I mean") in various contexts. For example, if we use a string containg "42" as a number we expect it automagically act as a number. Perl 6 keeps this tradition of DWIMmery and introduces several new explicit coercion operations.

? to get booleans
+ to get numbers
~ to get strings

These are all prefix unary operators.

? ''       # Bool::False, because '' is a kind of false
? 42       # Bool::True
+ '1'      # 1
~ 3e4      # '30000'

These operators ('+', '~', '?') allow you to explicitly coerce values to the types you expect. This can lead to code that is more "self-documenting", rather than relying on implicit type coercion.

Where these operators really shine is when you overload them as part of an object's API. This can let you provide all sorts of API cleverness, which some people will love and others will hate.

Here is a simple overloading example with a Roman numeral class. This object provides the Roman numeral in a string context, but acts like a regular integer when you do arithmetic.

my $x = Roman.new(42);
print ~$x; # 'XLII'
print +$x; # 42
"in the year {$x} of the Hyborian era" #[
     'in the year XLIV of the Hyborian era' ]
$x == 42; # Bool::True
print $x + 1; # 43
print ~($x + 1); # 'XLIII'

As you might have guessed from the examples so far, in Perl 6 we now have a proper boolean type Bool, which provides two values: Bool::True and Bool::False. Of course, because of DWIMmery, you can use other types of values in a boolean context and get sane results.

So why booleans? Well, without a proper boolean type in Perl 5, we had to fall back on representing boolean values using integers or strings. These types allow many values besides just { 0, 1 } or { '', 'true' }, which can cause confusion, especially if you end up with other true values like "maybe" or 10 in the mix.

See Also

The article on the string concatenation operator

$Revision: 45 $