String Operators
There is also an “addition” operator for strings that performs
concatenation (that is, joining strings end to end). Unlike some
languages that confuse this with numeric addition, Perl defines a
separate operator (.) for string
concatenation:
$a = 123; $b = 456; say $a + $b; # prints 579 say $a . $b; # prints 123456
There’s also a “multiply” operator for strings, called the
repeat operator. Again, it’s a separate operator
(x) to keep it distinct from numeric
multiplication:
$a = 123; $b = 3; say $a * $b; # prints 369 say $a x $b; # prints 123123123
These string operators bind as tightly as their corresponding arithmetic operators. The repeat operator is a bit unusual in taking a string for its left argument but a number for its right argument. Note also how Perl is automatically converting from numbers to strings. You could have put all the literal numbers above in quotes, and it would still have produced the same output. Internally, though, it would have been converting in the opposite direction (that is, from strings to numbers).
A couple more things to think about. String concatenation is also implied by the interpolation that happens in double-quoted strings. And when you print out a list of values, you’re also effectively concatenating strings. So the following three statements produce the same output:
say $a . " is equal to " . $b . "."; # dot operator say $a, " is equal to ", $b, "."; # list say "$a is equal to $b."; # interpolation
Which of these you use in any ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access