Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I use instead of printf in Perl?

I need to use some string replacement in Perl to ease translations, i.e. replace many

print "Outputting " . $n . " numbers";

by something like

printf ("Outputting %d numbers", $n);

However, I'd like to replace printf with something easier to parse for humans, like this:

printX ("Outputting {num} numbers", { num => $n });

or generally something more Perly.

Can you recommend something (from CPAN or not) you like and use?

like image 977
Nikolai Prokoschenko Avatar asked Apr 17 '09 11:04

Nikolai Prokoschenko


2 Answers

What about simply:

 print "Outputting $n numbers";

That's very Perly. If you don't need any kind of fancy formatting, string interpolation is definitely the way to go.

like image 108
Greg Hewgill Avatar answered Oct 04 '22 19:10

Greg Hewgill


Most Templating modules on CPAN will probably do what you want. Here's an example using Template Toolkit...

use Template;
my $tt = Template->new;

$tt->process( \"Outputting [% num %] numbers\n", { num => 100 } );


And you can mimic your required example with something like this...

sub printX {
    use Template;
    my $tt = Template->new( START_TAG => '{', END_TAG => '}' );
    $tt->process( \( $_[0] . "\n" ), $_[1] );
}

and you've got...

printX 'Outputting {num} numbers' => { num => 100 };
like image 25
draegtun Avatar answered Oct 04 '22 19:10

draegtun