Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Perl string interpolation perform any expression evaluation?

related to question: How do I substitute with an evaluated expression in Perl?

In Perl, is there a way like in Ruby to do:

$a = 1; print "#{$a + 1}"; 

and it can print out 2?

like image 849
nonopolarity Avatar asked Oct 15 '10 06:10

nonopolarity


People also ask

Can we use expressions Inside string interpolation?

Using string interpolation, we can use objects and expressions as a part of the string interpolation operation. C# string interpolation is a method of concatenating, formatting and manipulating strings. This feature was introduced in C# 6.

What is the purpose of string interpolation?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

What is Perl interpolation?

Interpolation in Perl refers to the process where the respective values replace the variable names. It is commonly used inside double-quoted strings.

What is string interpolation better known as?

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.


2 Answers

There's a similar shorthand in Perl for this:

$a = 1; print "@{[$a + 1]}" 

This works because the [] creates a reference to an array containing one element (the result of the calculation), and then the @{} dereferences the array, which inside string interpolation prints each element of the array in sequence. Since there is only one, it just prints the one element.

like image 107
Greg Hewgill Avatar answered Nov 12 '22 01:11

Greg Hewgill


You can use the @{[ EXPRESSION ]} trick that Greg Hewgill mentioned.

There's also the Interpolation module, which allows you to do arbitrary transformations on the values you're interpolating (like encode HTML entities) in addition to evaluating expressions.

like image 30
cjm Avatar answered Nov 12 '22 03:11

cjm