Python equivalent string formatting with dictionary in Perl with hashes

I like how Python can format a string with a dictionary:

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

I want to achieve the same thing in Perl with a hash. Is there any fragment or small library?

EDIT:

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; } 

It just works. This is not as complete as formatting a Python string with a dictionary, but I would like to improve this.

+3
source share
3 answers

From the python documentation:

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

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 that uses named parameters:

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

You can write this 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); } 

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

+4
source

Not quite sure what happened with line interpolation here.

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

Source: https://habr.com/ru/post/913572/


All Articles