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

我喜欢 Python用字典格式化字符串的方式:

print "%(key1)s and %(key2)s" % aDictObj

我想用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;
}

它只是有效.这不像使用字典的Python字符串格式那样功能完整,但我想改进它.

解决方法

从python文档:

The effect is similar to the using sprintf() in the C language.

所以这是使用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. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...