Perl 字符串插值可以执行任何表达式计算吗? [英] Can Perl string interpolation perform any expression evaluation?

查看:20
本文介绍了Perl 字符串插值可以执行任何表达式计算吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与问题相关:如何用 Perl 中的计算表达式替换?>

在 Perl 中,是否有类似 Ruby 的方法:

$a = 1;打印#{$a + 1}";

它可以打印出2?

解决方案

Perl 中有一个类似的简写:

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

这是有效的,因为 [] 创建了对包含一个元素(计算结果)的数组的引用,然后 @{} 取消引用该数组,其中字符串插值按顺序打印数组的每个元素.因为只有一个,所以只打印一个元素.

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?

解决方案

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.

这篇关于Perl 字符串插值可以执行任何表达式计算吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆