Vie*_*iet 4 perl hash dictionary string-formatting
我喜欢Python用字典格式化字符串的方式:
print "%(key1)s and %(key2)s" % aDictObj
Run Code Online (Sandbox Code Playgroud)
我想用Perl在Perl中实现同样的功能.是否有任何代码段或小型库可以执行此操作?
谢谢你试试这个答案.至于我,我出了一小段代码:
sub dict_replace
{
my ($tempStr, $tempHash) = @_;
my $key;
foreach $key (sort keys %$tempHash) {
my $tmpTmp = $tempHash->{$key};
$tempStr =~ s/%\($key\)s/$tmpTmp/g;
}
return $tempStr;
}
Run Code Online (Sandbox Code Playgroud)
它只是有效.这不像使用字典的Python字符串格式那样功能完整,但我想改进它.
从python文档:
效果类似于在C语言中使用sprintf().
my @ordered_list_of_values_to_print = qw(key1 key2);
printf '%s and %s', @ordered_list_of_values_to_print;
Run Code Online (Sandbox Code Playgroud)
还有一个新模块使用命名参数来完成它:
use Text::sprintfn;
my %dict = (key1 => 'foo', key2 => 'bar');
printfn '%(key1)s and %(key2)s', \%dict;
Run Code Online (Sandbox Code Playgroud)