8. String Interpolation

Perl supports inserting variables into string constants simply by placing their name along with the dollars inside them. Here's an example:

use strict;
use warnings;

my $name;
print "Please enter your name:\n";
$name = <>;
chomp($name);
print "Hello, $name!\n";

Note that once perl encounters a $-sign, it will try to use as many characters as possible from the string as the variable name, even if a variable by that name does not exist. Therefore, if you write $ab inside a string, it will not take the value of $a and append the string "b" to it! To overcome this limitation, you can limit the variable name using curly braces: "Hello ${boy}and${girl}".

In any case, interpolation is especially useful for building regular expression, since the string may contain control characters.


Written by Shlomi Fish