Contents Up Prev Next

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 perl will try to match as much as possible from the variable name, even if a variable by that name does not exist. Thus if you write $ab inside a string, it will not take $a and append "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.


Contents Up Prev Next