views:

75

answers:

2

related to question: http://stackoverflow.com/questions/3939788/perl-regex-substituion/3939854

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

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

and it can print out 2?

+7  A: 

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.

Greg Hewgill
There is another option `"${\\($a+1)}"` but I prefer former for readability sake.
Hynek -Pichi- Vychodil
+2  A: 

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.

cjm
+1 kinda neat, even if it is a bit clunky and uses ties.
Axeman