### Functional interface
use String::Print qw/printi printp/, %config;
# interpolation of arrays and hashes
printi 'age {years}', years => 12;
printi 'price-list: {prices%.2f}', prices => \@prices, _join => "+";
printi 'dump: {hash}', hash => \%config;
# same with positional parameters
printp 'age %d", 12;
printp 'price-list: %.2f', \@prices;
printp 'dump: %s', \%settings;
### Object Oriented interface
use String::Print 'oo'; # import nothing
my $f = String::Print->new(%config);
# same, called directly
$f->printi('age {years}', years => 12);
$f->printp('age %d', 12);
### via Log::Report's __* functions
use Log::Report::Optional;
print __x"age {years}", years => 12;
This module inserts values into (translated) strings. It provides "printf" and "sprintf" alternatives via both an object oriented and a functional interface.
Read in the "DETAILS" chapter below, why this module provides a better alternative for "printf()". Also, some extended examples can be found there. Take a look at them first, when you start using this module!
See functions printi(), sprinti(), printp(), and sprintp(): you can also call them as method.
use String::Print 'oo'; my $f = String::Print->new(%config); $f->printi($format, @params); # exactly the same functionality: use String::Print 'printi', %config; printi $format, @params;
The Object Oriented interface wins when you need the same configuration in multiple source files, or when you need different configurations within one program. In these cases, the hassle of explicitly using the object has some benefits.
-Option --Default
modifiers [ qr/^%\S+/ = \&format_printf]>
serializers <useful defaults>
example:
my $f = String::Print->new
( modifiers => [ EUR => sub {sprintf "%5.2f e", $_[0]} ]
, serializers => [ UNDEF => sub {'-'} ]
);
$f->printi("price: {p EUR}", p => 3.1415); # price: XX3.14 e
$f->printi("count: {c}", c => undef); # count: -
See section "Interpolation: Modifiers" about the details.
The functional interface creates a hidden object. You may import any of these functions explicitly, or all together by not specifying the names.
open my $fh, '>', $file;
printi $fh, ...
printi \*STDERR, ...
The PAIRS (which may be passed as LIST or HASH) contains a mixture of special and normal variables to be filled in. The names of the special variables (the options) start with an underscore ("_").
-Option --Default
_append undef
_count undef
_join ', '
_prepend undef
It may be useful to know that the positional $format is rewritten and then fed into sprinti(). Be careful with the length of the LIST: superfluous parameter PAIRS are passed along to "sprinti()", and should only contain "specials".
example: of the rewrite
# positional parameters
my $x = sprintp "dumpfiles: %s\n", \@dumpfiles
, _join => ':';
# is rewriten into, and then processed as
my $x = sprinti "dumpfiles: {filenames}\n"
, filenames => \@dumpfiles, _join => ':';
The "printf()" function is provided by Perl's CORE; you do not need to install any module to use it. Why would you use consider using this module?
To fill-in a FORMAT, three clearly separated components play a role:
Simplified:
# sprinti() replaces "{$key$modifiers$conversion}" by
$conversion->($serializer->($modifiers->($args{$key})))
# sprintp() replaces "%pos{$modifiers}$conversion" by
$conversion->($serializer->($modifiers->($arg[$pos])))
Example:
printi "price: {price X %-10s}", price => $cost;
printp "price: %-10{X}s", $cost;
$conversion = column width %-10s
$serializer = show float as string
$modifier = X to local currency
$value = $cost (in X)
The 'interpolation' functions have named VARIABLES to be filled-in, but also additional OPTIONS. To distinguish between the OPTIONS and VARIABLES (both a list of key-value pairs), the keys of the OPTIONS start with an underscore "_". As result of this, please avoid the use of keys which start with an underscore in variable names. On the other hand, you are allowed to interpolate OPTION values in your strings.
There is no way of checking beforehand whether you have provided all values to be interpolated in the translated string. When you refer to value which is missing, it will be interpreted as "undef".
printi "matching files: {files}", files => \@files, _join => ', '
$key => $value, $key2 => $value2, ...
There is no quoting on the keys or values (yet). Usually, this will produce an ugly result anyway.
serialization => [ $myclass => \&name_in_reverse ]
sub name_in_reverse($$$)
{ my ($formatter, $object, $args) = @_;
# the $args are all parameters to be filled-in
scalar reverse $object->name;
}
Modifiers are used to change the value to be inserted, before the characters get interpolated in the line.
Modifiers: unix format
Next to the name, you can specify a format code. With (gnu) "gettext()", you often see this:
printf gettext("approx pi: %.6f\n"), PI;
Locale::TextDomain has two ways:
printf __"approx pi: %.6f\n", PI;
print __x"approx pi: {approx}\n", approx => sprintf("%.6f", PI);
The first does not respect the wish to be able to reorder the arguments during translation (although there are ways to work around that) The second version is quite long. The content of the translation table differs between the examples.
With "Log::Report", above syntaxes do work, but you can also do:
# with optional translations
print __x"approx pi: {pi%.6f}\n", pi => PI;
The base for "__x()" is the printi() provided by this module. Internally, it will call "printi" to fill in parameters:
printi "approx pi: {pi%.6f}\n", pi => PI;
Another example:
printi "{perms} {links%2d} {user%-8s} {size%10d} {fn}\n"
, perms => '-rw-r--r--', links => 7, user => 'me'
, size => 12345, fn => $filename;
An additional advantage is the fact that not all languages produce comparable length strings. Now, the translators can take care that the layout of tables is optimal. Above example in printp() syntax, shorter but less maintainable:
printp "%s %2d %-8s 10d %s\n" , '-rw-r--r--', 7, 'me', 12345, $filename;
Modifiers: unix format improvements
The POSIX "printf()" does not handle unicode strings. Perl does understand that the 's' modifier may need to insert utf8 so does not count bytes but characters. "printi()" does not use characters but "grapheme clusters" via Unicode::GCString. Now, also composed characters do work correctly.
Additionally, you can use the new 'S' conversion to count in columns. In fixed-width fonts, graphemes can have width 0, 1 or 2. For instance, Chinese characters have width 2. When printing in fixed-width, this 'S' is probably the better choice over 's'. When the field does not specify its width, then there is no performance penalty for using 'S'.
Modifiers: private modifiers
You may pass your own modifiers. A modifier consists of a selector and a CODE, which is called when the selector matches. The selector is either a string or a regular expression.
# in Object Oriented syntax:
my $f = String::Print->new
( modifiers => [ qr/[XX]/ => \&money ]
);
# in function syntax:
use String::Print 'printi', 'sprinti'
, modifiers => [ qr/[XX]/ => \&money ];
# the implementation:
sub money$$$$)
{ my ($formatter, $modif, $value, $args) = @_;
$modif eq 'X' ? sprintf("%.2f EUR", $value+0.0001)
: $modif eq 'X' ? sprintf("%.2f GBP", $value/1.16+0.0001)
: 'ERROR';
}
Using printp() makes it a little shorter, but will become quite complex when there are more parameter in one string.
printi "price: {pX}", p => $pi; # price: 3.14 EUR
printi "price: {pX}", p => $pi; # price: 2.71 GBP
printp "price: %{X}s", $pi; # price: 3.14 EUR
printp "price: %{X}s", $pi; # price: 2.71 GBP
This is very useful in the translation context, where the translator can specify abstract formatting rules. As example, see the (GNU) gettext files, in the translation table for Dutch into English. The translator tells us which currency to use in the display.
msgid "kostprijs: {pX}"
msgstr "price: {pX}"
Another example. Now, we want to add timestamps. In this case, we decide for modifier names in "\w", so we need a blank to separate the parameter from the modifer.
use POSIX qw/strftime/;
use String::Print modifiers => [ qr/T|DT|D/ => \&_timestamp ];
sub _timestamp($$$$)
{ my ($formatter, $modif, $value, $args) = @_;
my $time_format
= $modif eq 'T' ? '%T'
: $modif eq 'D' ? '%F'
: $modif eq 'DT' ? '%FT%TZ'
: 'ERROR';
strftime $time_format, gmtime($value);
};
printi "time: {t T}", t => $now; # time: 10:59:17
printi "date: {t D }", t => $now; # date: 2013-04-13
printi "both: {t DT}", t => $now; # both: 2013-04-13T10:59:17Z
printp "time: %{T}s", $now; # time: 10:59:17
printp "date: %{D}s", $now; # date: 2013-04-13
printp "both: %{DT}s", $now; # both: 2013-04-13T10:59:17Z
Modifiers: stacking
You can add more than one modifier. The modifiers detect the extend of their own information (via a regular expression), and therefore the formatter understands where one ends and the next begins.
The modifiers are called in order:
printi "price: {pX%9s}\n", p => $p; # price: XXX123.45
printi ">{t T%10s}<", t => $now; # >XX12:59:17<
printp "price: %9{X}s\n", $p; # price: XXX123.45
printp ">%10{T}s<", $now; # >XX12:59:17<
There are a quite a number of modules on CPAN which extend the functionality of "printf()". To name a few: String::Format <http://search.cpan.org/~darren/String-Format>, String::Errf <http://http://search.cpan.org/~rjbs/String-Errf>, String::Formatter <http://http://search.cpan.org/~rjbs/String-Formatter>, Text::Sprintf::Named <http://search.cpan.org/~shlomif/Text-Sprintf-Named>, Acme::StringFormat <http://search.cpan.org/~gfuji/Acme-StringFormat>, Text::sprintf <http://search.cpan.org/~sharyanto/Text-sprintfn>, Log::Sprintf <http://search.cpan.org/~frew/Log-Sprintf>, and String::Sprintf <http://search.cpan.org/~bartl/String-Sprintf>. They are all slightly different.
When the "String::Print" module was created, none of the modules mentioned above handled unicode correctly. Global configuration of serializers and modifiers is also usually not possible, sometimes provided per explicit function call. Only "String::Print" cleanly separates the roles of serializers, modifiers, and conversions.
"String::Print" is nicely integrated with Log::Report.
This module is part of String-Print distribution version 0.15, built on March 14, 2014. Website: http://perl.overmeer.net/log-report/
Copyrights 2013-2014 by [Mark Overmeer]. For other contributors see ChangeLog.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html