我喜欢 Python 可以用字典格式化字符串的方式:
print "%(key1)s and %(key2)s" % aDictObj
我想用哈希在 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;
}
它只是工作。这不像使用字典的 Python 字符串格式化那样功能完整,但我想对此进行改进。
最佳答案
从python文档:
The effect is similar to the using sprintf() in the C language.
所以这是使用
printf
的解决方案或 sprintf
my @ordered_list_of_values_to_print = qw(key1 key2);
printf '%s and %s', @ordered_list_of_values_to_print;
还有一个使用命名参数的新模块:
use Text::sprintfn;
my %dict = (key1 => 'foo', key2 => 'bar');
printfn '%(key1)s and %(key2)s', \%dict;
关于perl - 在 Perl 中使用带有哈希的字典的 Python 等效字符串格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7950530/