Variable Interpolation

Perl's variable interpolation gives you more flexibility when it comes to handling strings.

So far, we have used double-quote marks when assigning a string to a variable:

$output_line = "Hello\n";   # 'Hello' followed by a new-line character


What if we wanted the string to contain the character "\" followed by the character "n" and not the special new line character?

We can specify a string explictly by enclosing it in single quotes instead of double quotes:

$output_line = 'Hello\n';   # 'Hello' followed by '\' followed by 'n'

The string is interpreted exactly as written.

When you use double-quotes, Perl using variable interpolation to interpret the string. Variable interpolation means that variables inside the string are interpreted before they are operated on. Using variable interpolation, you can build strings without having to use the concatenation operator.



Here's a simple example:
$first_name = 'Joe';
$last_name = 'Programmer';
$full_name = '$first_name $last_name\n';  
print $full_name;

No variable interpolation was used here. The output shows that the string has been interpreted literally.

$first_name $last_name\n



Here's more likely what we wanted, using variable interpolation:
$first_name = 'Joe';
$last_name = 'Programmer';
$full_name = "$first_name $last_name\n";   # variable interpolation
print $full_name;

Output:

Joe Programmer