String concatenation operator .
You can concatenate strings using the string concatenation operator ".".
my $str3 = $str1 . $str2;
This is an example to concatenate strings.
my $str1 = 'ABC'; my $str2 = 'DEF'; my $str3 = $str1 . $str2;
The string "$str3" becomes "ABCDEF".
Note that Perl does not concatenate strings with the addition operator "+". "+" Is used to add numbers.
How to use with variable expansion
If the string consists only of variable, it is easy to write using variable expansion.
my $str1 = 'ABC'; my $str2 = 'DEF'; my $str3 = "$str1 $str2";
The string concatenation operator is useful when used in combination with functions.
my @nums = (1, 2, 3); my $title = 'Number:'; my $output = $title . join(',', @nums) . "\n";
Reference: join function
Special assignment operator
You can use the special assignment operator ".=" to concatenate to its own string.
my $str1 = 'ABC'; $str1 .= 'DEF';
The string "$str1" becomes "ABCDEF".
Repeat operator
You can use the repeat operator "x" to concatenate the same string multiple times.
my $str = 'ABC' x 3;
The string "$str" becomes "ABCABCABC".
Example program
This is an example to concatenate strings.
use strict; use warnings; # 1: String concatenation my $str1 = "1"; my $str2 = "2"; print "\$str1 = $str1\n"; print "\$str2 = $str2\n\n"; my $cat_str = $str1 . $str2; print "1: String concatenation\n"; print "\$cat_str = $cat_str\n\n"; print "If you connect with +, it will be calculated\n"; my $sum_str = $str1 + $str2; print "\$sum_str = $sum_str\n\n"; # 2: Repeat and concatenate the same string. my $multi_cat_str = $str1 x 5; print "2: Repeated concatenation\n"; print "\$multi_cat_str = $multi_cat_str\n";
Output:
$str1 = 1 $str2 = 2 1: String concatenation $cat_str = 12 If you connect with +, it will be calculated $sum_str = 3 2: Repeated concatenation $multi_cat_str = 11111