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?
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 feature-complete as Python string-formatting with a dictionary but I’d like to improve on that.
From the python documentation:
So this is a solution using
printforsprintfThere is also a new module which does it using named parameters: