我想回答这个问题
要获得 Perl 的所有花哨格式和对哈希数据的键控访问,您需要一个(更好的版本)函数:
# 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 字符串的正则表达式吗?