Can Perl string interpolation perform any expression evaluation?

前端 未结 2 643
旧时难觅i
旧时难觅i 2020-12-08 04:25

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}\         


        
相关标签:
2条回答
  • 2020-12-08 04:45

    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.

    0 讨论(0)
  • 2020-12-08 04:58

    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.

    0 讨论(0)
提交回复
热议问题