Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred way of interpolating a constant in a here doc?

Tags:

perl

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
like image 576
gcbenison Avatar asked Apr 03 '13 16:04

gcbenison


People also ask

What is the use of string interpolation?

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.

What is interpolation PHP?

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.

Which strings do interpolate variables?

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.


1 Answers

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;
like image 104
amon Avatar answered Oct 29 '22 21:10

amon