文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>1.15 字符串里面内插函数和表达式(翻译中)

1.15 字符串里面内插函数和表达式(翻译中)

时间:2007-01-09  来源:xiaoshengcaicai

1.15 字符串里面内插函数和表达式

1.15.1 问题

你想在字符串里面进行函数调用或者表达式扩展。比起字符串里面内插简单的标量变量,你需要构造更复杂的模板。

1.15.2 解决方案

把你的表达式分割成几个部分再连起来:

$answer = $var1 . func( ) . $var2; # scalar only

或者使用稍微有点猥琐的@{[ LIST EXPR ]} 或者 ${ \(SCALAR EXPR ) } 进行扩展:

$answer = "STRING @{[ LIST EXPR ]} MORE STRING";
$answer = "STRING ${\( SCALAR EXPR )} MORE STRING";

1.15.3 讨论

这个代码表达了2种技术,第一行表达的是连接(concatenation),第二行表达的是扩展技巧:

$phrase = "I have " . ($n + 1) . " guanacos.";
$phrase = "I have ${\($n + 1)} guanacos.";

第一种技术通过连接短字符串,避免了字符串内插,这样结果是一样的。因为print函数也只是把它的整个参数列表连接起来, 在这里如果我们只想打印$phrase,我们只需这样写:

print "I have ", $n + 1, " guanacos.\n";

如果你肯定要用内插的话,你需要像解决方案里面那样进行内插(punctuation-riddled interpolation)。在双引号和其他大多数反引号里面只有@,$,\是特别的字符。(像m//,s///,qx()等这样的如果使用了单引号的定界符,那么它们不能像跟双引号引用那样进行扩展。$home = qx'echo home is $HOME';这行代码最后会打印出shell环境变量$HOME,而不是Perl的变量$HOME),所以,要进行强制进行表达式扩展的唯一方法是使用${ } 或者 @{ }内带一个引用进行扩展。

在例子里面:

$phrase = "I have ${\( count_em( ) )} guanacos.";
count_em这个函数调用并不是在标量上下文里面,它仍然是在处于列表上下文,如果要使用标量上下文就这样:
$phrase = "I have ${\( scalar count_em( ) )} guanacos.";

在完成字符串里面的内插后,并不仅仅只能用来赋值,你可以把它当成一个一般的字符串使用,下面这个例子把内插扩展后的字符串传给了一个函数:

some_func("What you want is @{[ split /:/, $rec ]} items");

你还可以像下面这样内插一个当前文档(here document):

die "Couldn't send mail" unless send_mail(<<"EOTEXT", $target);
To: $naughty
From: Your Bank
Cc: @{ get_manager_list($naughty) }
Date: @{[ do { my $now = `date`; chomp $now; $now } ]} (today)

Dear $naughty,

Today, you bounced check number @{[ 500 + int rand(100) ]} to us.
Your account is now closed.

Sincerely,
the management
EOTEXT

Expanding backquotes (``) is particularly challenging because you would normally end up with spurious newlines. By creating a braced block following the @ within the @{[ ]} anonymous array dereference, as in the last example, you can create private variables.

Although these techniques work, simply breaking your work up into several steps or storing everything in temporary variables is almost always clearer to the reader.

The Interpolation module from CPAN provides a more syntactically palatable covering. For example, to make elements of the hash %E evaluate and return its subscript:

use Interpolation E => 'eval';
print "You bounced check number $E{500 + int rand(100)}\n";

Or to make a hash named %money call a suitably defined function of your choice:

use Interpolation money => \&currency_commify;

print "That will be $money{ 4 * $payment }, right now.\n";

expect to get something like:

That will be $3,232.421.04, right now.

1.15.4 See Also

perlref(1) and the "Other Tricks You Can Do with Hard References" section in Chapter 8 of Programming Perl; the Interpolation CPAN module

相关阅读 更多 +
排行榜 更多 +
试着飞手游下载

试着飞手游下载

休闲益智 下载
血染小镇(功能菜单)中文版下载

血染小镇(功能菜单)中文版下载

飞行射击 下载
泰坦之旅高爆版下载

泰坦之旅高爆版下载

角色扮演 下载