Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-equivalent string formatting with dictionary in Perl with hashes

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.

like image 566
Viet Avatar asked Jan 18 '23 09:01

Viet


2 Answers

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;
like image 155
stevenl Avatar answered Jan 31 '23 07:01

stevenl


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.

like image 34
jfs Avatar answered Jan 31 '23 09:01

jfs