Yet Another Perl 6 Operator: Stitching

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 '~' instead of '.' as in Perl 5. Think of it as "stitching" the two ends of its arguments together (S03).

Appending to a string can be done with '~='. (Similar to '+=' for addition).

$c ~= "xyz"; # 'abcdefxyz'
my $d = $a;
$d ~= $b; # 'abcdef'

The infix operator '~' has the same precedence as '+' in Perl 6. The tilde is consistently employed for string operations and fits nicely with the unary '~' which coerces its argument to strings. There is also a prefix '~', used in operators like '~|', to perform bitwise operations on sequences of bits.

String interpolation can still be thought of in terms of concatenation, meaning "Answer = $answer\n" is equivalent to 'Answer = ' ~ $answer ~ "\n".

While this breaks compatibility with Perl 5, this break is quite important, since it frees up '.' for other uses. Nowadays, is is common OO practice to use the '.' operator to join together the invocant object and an object member (attribute, method, etc.).

The Perl 6 design does have many cases where it breaks backwards compatibility with Perl 5, but it does this in the service of a greater cause, consistency.

$Revision: 30 $