使用哈希表在Perl中实现类似Python的字典字符串格式化

4

我喜欢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字符串格式化功能完整,但我希望对此进行改进。


1
你正在寻找Text::Template吗?http://search.cpan.org/perldoc?Text::Template - DavidO
谢谢David。然而,它不像Python那样优雅。 - Viet
那么,您是在建议像这样的东西吗?%aDictObj = ( definitions => here ); print "$_->{key1}s and $_->{key2}s" for \%aDictObj; - DavidO
Data::Dumper怎么样?http://search.cpan.org/~smueller/Data-Dumper-2.131/Dumper.pm - Mr_Spock
谢谢 Spock。这不是我正在寻找的内容。 - Viet
3个回答

5

来自Python文档:

该效果类似于在C语言中使用sprintf()。

因此,这是一种使用printfsprintf的解决方案。

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;

1
使用字典进行格式化与C printf()完全不同。它允许根据名称而不是参数列表中的位置来指定在构建字符串时要使用哪个参数。 - Adrien Plisson
"cpan Text::sprintfn" 无法工作:无法安装Text::sprintfn,也不知道它是什么。 - jfs
2
J.F. Sebastian,有一个索引错误或其他问题。请使用更合适的符号SHARYANTO/Text-sprintfn-0.03.tar.gz进行安装。 - daxim

4

您可以这样编写:

say format_map '{$key1} and {$key2}', \%aDictObj

If you define:

sub format_map($$) {
 my ($s, $h) = @_;
 Text::Template::fill_in_string($s, HASH=>$h);
}

这是Python中"{key1} and {key2}".format_map(aDictObj)的直接等价。

0

不太确定这里的字符串插值有什么问题。

print "$aDictObj{key1} and $aDictObj{key2}\n";

Perl的字符串插值不如Python使用字典进行字符串格式化灵活。 - Viet
print "%(key1)s and %(key2)s" % aDictObjprint "$aDictObj{key1} and $aDictObj{key}" 实际上是相同的。Python 版本如何更加灵活? - flesk
@flesk:Viet 可能意味着你可以在 Python 版本中使用宽度、精度说明符等。 - jfs
然后你又回到了printf()。还是没问题的。 - mwp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接