Strings Interpolation
Learn string interpolation in this lesson with the help of examples.
We'll cover the following
We have already covered the creation of strings in the previous lesson. Here, we will discuss the various techniques to format and manipulate strings.
String interpolation
The term interpolation refers to the insertion of a variable within a string. Interpolation works in double-quoted strings ""
only.
$name = 'Leo';print "Hello $name, Nice to see you.";# $name will be replaced with `Leo`
Notice that in line 2 of the above code, we used double quotes. If we use single quotes, the compiler will output $name
as the $name
and not replacing it with Leo
. This is shown in the following code snippet:
$name = 'Leo';print 'Hello $name, Nice to see you.';# does not interpret $name as Leo
Complex syntax
In Perl, you can also use the complex syntax which requires that you use a variable before backslash \
. This can be useful when embedding variables within the text and helps prevent possible ambiguity between text and variables. This is shown in the following code snippet:
$name = 'Joel';# Example using the \ syntax for the variable $nameprint "We need more $name\s to help us!\n";