In Perl, the dot operator (.) is used for explicit string concatenation. Historically, this approach in Perl has been more convenient than in many other languages and is often applied for string addition or dynamic messages. Concatenation is handled as a string operation, which can often lead to subtle errors.
Background:
Since the early days, Perl introduced an explicit operator for string concatenation to distinguish it from numeric addition — because + in Perl is always numeric.
Problem:
The main issue is implicit type conversion. Perl automatically converts values to strings when a dot (.) is involved in an expression, but this can lead to unexpected results when working with numbers, undef, or complex structures.
Solution:
Use the dot only for string concatenation and be careful when mixing types. Strive to explicitly convert data to strings if you are unsure of the type.
Code example:
my $a = 20; my $b = ' apples'; my $c = $a . $b; # $c will be '20 apples' my $d = undef; my $s = 'Answer: ' . $d; # $s is 'Answer: '
Key features:
+ always adds numbersWhat happens when concatenating undef and a string?
Perl converts undef to an empty string without warning. This can lead to output errors if meaningful information was expected.
What is the difference between operators ".=" and "=" when working with strings?
.= is the assignment operator with concatenation (it appends to the string), = is straightforward assignment. The difference is critical in cyclic operations and when handling large data.
my $str = "a"; $str .= "b"; # str = "ab" $str .= "c"; # str = "abc"
Can the dot (.) be mistakenly interpreted as part of a number (e.g., in a decimal)?
No, within expressions Perl always distinguishes between . as concatenation and . as part of a number. However, in regular expressions, the dot has its meaning ("any character").
+ and . in a single expression without explicit type controlConcatenating numbers and strings without explicit type control, expecting "3 apples", but getting "12 apples".
Pros:
Cons:
All numbers are explicitly converted to strings, using the dot only for string operations.
Pros:
Cons: