← Back to Perl Course | Chapter 3: Strings | Lesson 2 of 7

Concatenation and repetition

The dot joins strings together and x repeats them.

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

perl
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
Common Mistakes
  1. Using + to concatenate strings
  2. Forgetting that x with a negative count gives an empty string
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.