Interpolating Functions and Expressions Within Strings
Problem
You want a function call or expression to expand within a string. This lets you construct more complex templates than with simple scalar variable interpolation.
Solution
You can break up your expression into distinct concatenated pieces:
$answer = $var1 . func() . $var2; # scalar only
Or you can use the slightly sneaky @{[
LIST
EXPR
]}
or ${
\(SCALAR
EXPR
)
}
expansions:
$answer = "STRING @{[ LIST EXPR ]} MORE STRING";
$answer = "STRING ${\( SCALAR EXPR )} MORE STRING";Discussion
This code shows both techniques. The first line shows concatenation; the second shows the expansion trick:
$phrase = "I have " . ($n + 1) . " guanacos.";
$phrase = "I have ${\($n + 1)} guanacos.";The first technique builds the final string by concatenating smaller
strings, avoiding interpolation but achieving the same end. Because
print effectively concatenates its entire argument
list, if we were going to print
$phrase, we could have just said:
print "I have ", $n + 1, " guanacos.\n";
When you absolutely must have interpolation, you need the
punctuation-riddled interpolation from the Solution. Only
@, $, and \
are special within double quotes and most backquotes. (As with
m// and s///, the
qx() synonym is not subject to double-quote
expansion if its delimiter is single quotes! $home
=
qx'echo
home
is
$HOME'; would get the shell
$HOME variable, not one in Perl.) So, the only way
to force arbitrary expressions to expand is by expanding a
${} or @{} ...