I love the way 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 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;
}
It just works. This is not as feature-complete as Python string-formatting with a dictionary but I'd like to improve on that.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With