Python-equivalent string formatting with dictionary in Perl with hashes

懵懂的女人 提交于 2019-12-04 10:05:57

From the python documentation:

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

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;

You could write it as:

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

If you define:

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

It is a direct equivalent of "{key1} and {key2}".format_map(aDictObj) in Python.

Not quite sure what's wrong with string interpolation here.

print "$aDictObj{key1} and $aDictObj{key2}\n";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!