String interpolation and concatenation are both important operations in Perl for dealing with strings. Let’s discuss each of them separately:
String Interpolation: String interpolation is the process of evaluating variables inside a string literal to their corresponding values. Perl supports string interpolation by using the double-quoted string literal syntax. Here is an example:
my $name = "John";
my $message = "Hello $name, how are you?";
print $message;
In the above example, the variable ‘$name‘ is interpolated inside the string literal to form the final string that is printed - "Hello John, how are you?". Note that string interpolation only works inside double-quoted string literals, and not in single-quoted literals.
Concatenation: Concatenation is the process of combining two or more strings into a single string. Perl uses the ‘.‘ operator to concatenate strings. Here is an example:
my $first_name = "John";
my $last_name = "Doe";
my $full_name = $first_name . " " . $last_name;
print $full_name;
In the above example, the ‘.‘ operator is used to concatenate the strings and form the final string that is printed - "John Doe". Note that the ‘.‘ operator can be used to concatenate any number of strings, not just two.
You can also perform concatenation using the ‘+=‘ operator, which is a shortcut for concatenating strings. Here is an example:
my $first_name = "John";
my $last_name = "Doe";
$first_name .= " " . $last_name;
print $first_name;
In the above example, the ‘.‘ operator and ‘+=‘ operator are used together to concatenate the strings and form the final string that is printed - "John Doe". Note that the ‘.=‘ operator modifies the value of the variable ‘$first_name‘ in place, so it now contains the concatenated string.