I'm sure there are several ways of getting the value 'bar' to interpolate in the <> below, but what is the cleanest way, and why?
use constant FOO => 'bar';
my $msg = <<EOF;
Foo is currently <whatever goes here to expand FOO>
EOF
String interpolation is a technique that enables you to insert expression values into literal strings. It is also known as variable substitution, variable interpolation, or variable expansion. It is a process of evaluating string literals containing one or more placeholders that get replaced by corresponding values.
Variable interpolation is adding variables in between when specifying a string literal. PHP will parse the interpolated variables and replace the variable with its value while processing the string literal.
String interpolation is common in many programming languages which make heavy use of string representations of data, such as Apache Groovy, Julia, Kotlin, Perl, PHP, Python, Ruby, Scala, Swift, Tcl and most Unix shells.
There are two kinds of here-docs:
<<'END'
, which behaves roughly like a single quoted string (but no escapes), and<<"END"
, also <<END
, which behaves like a double quoted string.To interpolate a value in a double quoted string use a scalar variable:
my $foo = "bar";
my $msg = "Foo is currently $foo\n";
Or use the arrayref interpolation trick
use constant FOO => "bar";
my $msg = "Foo is currently @{[ FOO ]}\n";
You could also define a template language to substitute in the correct value. This may or may not be better depending on your problem domain:
my %vars = (FOO => "bar");
my $template = <<'END';
Foo is currently %FOO%;
END
(my $msg = $template) =~ s{%(\w+)%}{$vars{$1} // die "Unknown variable $1"}eg;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With