Another article of the series “Yet Another Perl 6 Operator”

Today’s operator is a very simple one, the string concatenation operator.

my $a = 'ab' ~ 'c'; # 'abc'

my $b = 'def';
my $c = $a ~ $b; # 'abcdef'

The operator is now written '~' and not '.' as in Perl 5. Think of it as “stitching” the two ends of its arguments together (S03).

Appending to a string can likewise be done with '~='. (Compare to '+=' that adds to a number.)

$c ~= "xyz"; # 'abcdefxyz'

my $d = $a;
$d ~= $b; # 'abcdef'

The infix operator '~' keeps the same precedence as '+' in Perl 6. The tilde is consistently employed for string operations and fits nicely with the unary '~' that coerces its argument to strings and the prefix '~' (used in operators like '~|') to mean bitwise operations on arguments interpreted as long bit strings.

String interpolation is still built on terms of string concatenation, meaning "Answer = $answer\n" is equivalent to 'Answer = ' ~ $answer ~ "\n".

The compatibily break with Perl 5 was a rather important one, since '.' was after a few years of common OO practice the operator of choice to join together the invocant object and a member (attribute, method, etc.). The repurposing was a long awaited thing.

At the other hand, in Perl 5, '~' is no longer the bitwise not. If you look closer to Perl 6 design, you’ll see it is filled with these breaks with traditions for the sake of a greater cause: consistency.


Friday (September 21, 2007) will bring you the next article of the series.

More thanks to the folks at #perl6 (at irc.freenode.net) and at the perl6-language@perl.org mailing list.



LINKS