Interpolation and quoting
Scalars in strings
Inside double quotes Perl replaces a variable name with its value as the string is built. There is no format string to learn and no placeholder: the sigil is the marker.
my $user = "ada";
my $home = "/home/$user";
print "$user lives in $home\n";
perl demo.pl
ada lives in /home/ada
A backslash before the sigil stops the replacement and leaves the dollar sign in the text. That is how you print a literal amount such as a shell variable name:
print "cost: \$5\n"; # cost: $5
print "var: \$HOME\n"; # var: $HOME
perl demo.pl
cost: $5
var: $HOME
Braces disambiguate
Perl takes the longest valid name after the sigil. If a letter follows the variable, the parser thinks it belongs to the name and looks for a variable that does not exist. Wrap the name in braces to mark where it ends.
my $file = "app";
print "${file}s\n"; # apps, braces stop the name
print "${file}_log\n"; # app_log
perl demo.pl
apps
app_log
Arrays in strings
An array interpolates as its elements joined by spaces, which is handy for messages but dangerous for machine-readable output. Control the separator with join and an explicit expression instead.
my @args = qw(--fast --quiet);
print "args: @args\n"; # args: --fast --quiet
print "n=", scalar @args, "\n"; # n=2
perl demo.pl
args: --fast --quiet
n=2
A single element keeps the dollar sigil and puts the index in square brackets, because the at sign alone would interpolate the whole array:
my @args = qw(--fast --quiet);
print "first: $args[0]\n"; # first: --fast
print "last index: $#args\n"; # last index: 1
perl demo.pl
first: --fast
last index: 1
Heredocs
For several lines of text the heredoc syntax is easier than a pile of quotes. Write two angle brackets and an identifier, then the text, then the identifier alone on a line to close it.
The quoted form <<'END' behaves like single quotes and interpolates nothing, which is what you want for SQL, shell scripts and templates.
my $name = "Ada";
my $text = <<"END";
Hello $name,
this line is part of the string.
END
print $text;
perl demo.pl
Hello Ada,
this line is part of the string.
Escaping the sigil
When a string is mostly code and only partly data, quote the whole thing with q and interpolate nothing. The two approaches below build the same message; pick the one that keeps the sigils readable.
my $host = "db1";
print "ssh \$USER\@$host\n";
print qq{ssh \$USER\@$host\n};
perl demo.pl
ssh $USER@db1
ssh $USER@db1
Next: Arrays
Article author: Arthur Isaev