我希望能够回答这个问题并提供如下内容:
要想获得 Perl 所有的格式和哈希数据的键控访问,您需要一个(更好版本的)函数。以下是该函数的示例:this question。
要想获得 Perl 所有的格式和哈希数据的键控访问,您需要一个(更好版本的)函数。以下是该函数的示例:this question。
# sprintfx(FORMAT, HASHREF) - like sprintf(FORMAT, LIST) but accepts
# "%<key>$<tail>" instead of "%<index>$<tail>" in FORMAT to access the
# values of HASHREF according to <key>. Fancy formatting is done by
# passing '%<tail>', <corresponding value> to sprintf.
sub sprintfx {
my ($f, $rh) = @_;
$f =~ s/
(%%) # $1: '%%' for '%'
| # OR
% # start format
(\w+) # $2: a key to access the HASHREF
\$ # end key/index
( # $3: a valid FORMAT tail
# 'everything' upto the type letter
[^BDEFGOUXbcdefginosux]*
# the type letter ('p' removed; no 'next' pos for storage)
[BDEFGOUXbcdefginosux]
)
/$1 ? '%' # got '%%', replace with '%'
: sprintf( '%' . $3, $rh->{$2}) # else, apply sprintf
/xge;
return $f;
}
但我为使用冒险/蛮力方法捕获格式字符串的“尾部”感到羞愧。
那么:有没有可以信任的FORMAT字符串的正则表达式?
sprintf
中,%%
不是一个特殊情况?例如,sprintf('%2%')
将会产生字符串' %'
。 - Ven'Tatsu