Python等效的字符串格式与Perl中的字典哈希 [英] Python-equivalent string formatting with dictionary in Perl with hashes

查看:143
本文介绍了Python等效的字符串格式与Perl中的字典哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I love the way Python can format a string with a dictionary:

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

我想在Perl中实现与哈希一样的事情。有没有任何片段或小图书馆这样做?

I want to achieve the same thing in Perl with hashes. Is there any snippet or small library to do so?

感谢您尝试此答案。对于我来说,我出来了一小段代码:

Thanks for trying this answer. As for me, I came out with a short piece of code:

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

It just works. This is not as feature-complete as Python string-formatting with a dictionary but I'd like to improve on that.

推荐答案

从python文档:


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

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

所以这是一个使用 printf的解决方案 sprintf

So this is a solution using printf or sprintf

my @ordered_list_of_values_to_print = qw(key1 key2);
printf '%s and %s', @ordered_list_of_values_to_print;

还有一个新模块使用命名参数:

There is also a new module which does it using named parameters:

use Text::sprintfn;
my %dict = (key1 => 'foo', key2 => 'bar');
printfn '%(key1)s and %(key2)s', \%dict;

这篇关于Python等效的字符串格式与Perl中的字典哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆