Concatenation and repetition
The dot joins strings together and x repeats them.
In this page:
Concatenation and repetition
The . operator concatenates two strings, and .= appends to an existing variable. The x operator repeats a string a given number of times, which is useful for drawing lines. When x is used with a list in parentheses on its left it repeats the list instead of the string.
Note:
Interpolation is usually easier to read than a chain of . operators.
Example: Concatenation and repetition
use strict;
use warnings;
my $first = "Hello";
my $second = "World";
my $greeting = $first . ", " . $second . "!";
print "$greeting\n";
my $text = "abc";
$text .= "def";
print "$text\n";
print "-" x 20, "\n";
print "=" x 0, "|empty|\n";
my @zeros = (0) x 5;
print "zeros: @zeros\n";
print "Total: " . (2 + 3) . "\n";
# Output:
# Hello, World!
# abcdef
# --------------------
# |empty|
# zeros: 0 0 0 0 0
# Total: 5
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Using + to concatenate strings
- Forgetting that x with a negative count gives an empty string
- Writing (0) x 5 and expecting a string instead of a list
Chapter Summary
- . concatenates strings
- .= appends to a variable
- x repeats a string
- (list) x n repeats a list
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: