问题
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.
回答1:
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;
回答2:
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.
回答3:
Not quite sure what's wrong with string interpolation here.
print "$aDictObj{key1} and $aDictObj{key2}\n";
来源:https://stackoverflow.com/questions/7950530/python-equivalent-string-formatting-with-dictionary-in-perl-with-hashes