与Perl中的字典相对应的Python字符串格式,带有哈希

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字符串格式那样功能完整,但我想改进它.

ste*_*enl 5

从python文档:

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

所以这是一个使用printf或的解决方案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)

  • JF塞巴斯蒂安,有一个索引搞砸了什么.使用更合格的符号"SHARYANTO/Text-sprintfn-0.03.tar.gz"进行安装. (2认同)