/usr/share/perl5/String/Print.pod is in libstring-print-perl 0.15-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 | =encoding utf8
=head1 NAME
String::Print - printf alternative
=head1 SYNOPSIS
### 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;
=head1 DESCRIPTION
This module inserts values into (translated) strings. It provides
C<printf> and C<sprintf> alternatives via both an object oriented and a
functional interface.
Read in the L</DETAILS> chapter below, why this module provides a better
alternative for C<printf()>. Also, some extended B<examples> can be
found there. Take a look at them first, when you start using this
module!
=head1 METHODS
=head2 The Object Oriented interface
See functions L<printi()|String::Print/"FUNCTIONS">, L<sprinti()|String::Print/"FUNCTIONS">, L<printp()|String::Print/"FUNCTIONS">, and L<sprintp()|String::Print/"FUNCTIONS">: 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.
=head2 Constructors
=over 4
=item String::Print-E<gt>B<new>(%options)
-Option --Default
modifiers [ qr/^%\S+/ = \&format_printf]>
serializers <useful defaults>
=over 2
=item modifiers => ARRAY
Add one or more modifier handlers to power of the formatter. They will
get preference over the predefined modifiers, but lower than the modifiers
passed to C<print[ip]> itself.
=item serializers => HASH|ARRAY
How to serialize data elements.
=back
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: ␣␣3.14 e
$f->printi("count: {c}", c => undef); # count: -
=back
=head2 Attributes
=over 4
=item $obj-E<gt>B<addModifiers>(PAIRS)
The PAIRS are a combination of an selector and a CODE which processes the
value when the modifier matches. The selector is a string or (preferred)
a regular expression. Later modifiers with the same name overrule earlier
definitions. You may also specify an ARRAY of modifiers per C<print>.
See section L</"Interpolation: Modifiers"> about the details.
=back
=head1 FUNCTIONS
The functional interface creates a hidden object. You may import any of
these functions explicitly, or all together by not specifying the names.
=over 4
=item B<printi>( [$fh], $format, PAIRS|HASH )
Calls L<sprinti()|String::Print/"FUNCTIONS"> to fill the data in PAIRS or HASH in $format, and
then sends it to the $fh (by default the selected file)
open my $fh, '>', $file;
printi $fh, ...
printi \*STDERR, ...
=item B<printp>( [$fh], $format, PAIRS|HASH )
Calls L<sprintp()|String::Print/"FUNCTIONS"> to fill the data in PAIRS or HASH in $format, and
then sends it to the $fh (by default the selected file)
=item B<sprinti>($format, PAIRS|HASH)
The $format refers to some string, maybe the result of a translation.
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 (C<_>).
-Option --Default
_append undef
_count undef
_join ', '
_prepend undef
=over 2
=item _append => STRING|OBJECT
Text as STRING appended after $format, without interpolation.
=item _count => INTEGER
Result of the translation process: when Log::Report subroutine __xn is
are used for count-sensitive translation. Those function may add
more specials to the parameter list.
=item _join => STRING
Which STRING to use when an ARRAY is being filled-in as parameter.
=item _prepend => STRING|OBJECT
Text as STRING prepended before $format, without interpolation. This
may also be an OBJECT which gets stringified, but variables not filled-in.
=back
=item B<sprintp>($format, LIST, PAIRS)
Where L<sprinti()|String::Print/"FUNCTIONS"> uses named parameters --especially useful when the
strings need translation-- this function stays close to the standard
C<sprintf()>. All features of POSIX formats are supported. This
should say enough: you can use C<%3$0#5.*d>, if you like.
It may be useful to know that the positional $format is rewritten and
then fed into L<sprinti()|String::Print/"FUNCTIONS">. B<Be careful> with the length of the LIST:
superfluous parameter PAIRS are passed along to C<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 => ':';
=back
=head1 DETAILS
=head2 Why use C<printi()>, not C<printf()>?
The C<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?
=over 4
=item translating
C<printf()> uses positional parameters, where L<printi()|String::Print/"FUNCTIONS"> uses names
to refer to the values to be filled-in. Especially in a set-up with
translations, where the format strings get extracted into PO-files,
it is much clearer to use names. This is also a disadvantage of
L<printp()|String::Print/"FUNCTIONS">
=item pluggable serializers
C<printi()> supports serialization for specific data-types: how to
interpolate C<undef>, HASHes, etc.
=item pluggable modifiers
Especially useful in context of translations, the FORMAT string may
contain (language specific) helpers to insert the values correctly.
=item correct use of utf8
Sized string formatting in C<printf()> is broken: it takes your string
as bytes, not Perl strings (which may be utf8). In unicode, one
"character" may use many bytes. Also, some characters are displayed
double wide, for instance in Chinese. The L<printi()|String::Print/"FUNCTIONS"> implementation
will use Unicode::GCString for correct behavior.
=back
=head2 Three components
To fill-in a FORMAT, three clearly separated components play a role:
=over 4
=item 1. modifiers
How to change the provided values, for instance to hide locale
differences.
=item 2. serializer
How to represent (the modified) the values correctly, for instance C<undef>
and ARRAYs.
=item 3. conversion
The standard UNIX format rules, like C<%d>. One conversion rule
has been added 'S', which provides unicode correct behavior.
=back
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 € %-10s}", price => $cost;
printp "price: %-10{€}s", $cost;
$conversion = column width %-10s
$serializer = show float as string
$modifier = € to local currency
$value = $cost (in €)
=head2 Interpolation: Serialization
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 C<_>. 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 C<undef>.
=over 4
=item CODE
When a value is passed as CODE reference, that function will get called
to return the value to be filled in.
For interpolating, the following rules apply:
=item strings
Simple scalar values are interpolated "as is"
=item SCALAR
Takes the value where the scalar reference points to.
=item ARRAY
All members will be interpolated with C<,␣> between the elements.
Alternatively (maybe nicer), you can pass an interpolation parameter
via the C<_join> OPTION.
printi "matching files: {files}", files => \@files, _join => ', '
=item HASH
By default, HASHes are interpolated with sorted keys,
$key => $value, $key2 => $value2, ...
There is no quoting on the keys or values (yet). Usually, this will
produce an ugly result anyway.
=item Objects
With the C<serialization> parameter, you can overrule the interpolation
of above defaults, but also add rules for your own objects. By default,
objects get stringified.
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;
}
=back
=head2 Interpolation: Modifiers
Modifiers are used to change the value to be inserted, before the characters
get interpolated in the line.
=head3 Modifiers: unix format
Next to the name, you can specify a format code. With (gnu) C<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 C<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 C<__x()> is the L<printi()|String::Print/"FUNCTIONS"> provided by this module. Internally,
it will call C<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 L<printp()|String::Print/"FUNCTIONS"> syntax,
shorter but less maintainable:
printp "%s %2d %-8s 10d %s\n"
, '-rw-r--r--', 7, 'me', 12345, $filename;
=head3 Modifiers: unix format improvements
The POSIX C<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. C<printi()> does not use characters but
"grapheme clusters" via Unicode::GCString. Now, also composed
characters do work correctly.
Additionally, you can use the B<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'.
=head3 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/[€₤]/ => \&money ]
);
# in function syntax:
use String::Print 'printi', 'sprinti'
, modifiers => [ qr/[€₤]/ => \&money ];
# the implementation:
sub money$$$$)
{ my ($formatter, $modif, $value, $args) = @_;
$modif eq '€' ? sprintf("%.2f EUR", $value+0.0001)
: $modif eq '₤' ? sprintf("%.2f GBP", $value/1.16+0.0001)
: 'ERROR';
}
Using L<printp()|String::Print/"FUNCTIONS"> makes it a little shorter, but will become quite
complex when there are more parameter in one string.
printi "price: {p€}", p => $pi; # price: 3.14 EUR
printi "price: {p₤}", p => $pi; # price: 2.71 GBP
printp "price: %{€}s", $pi; # price: 3.14 EUR
printp "price: %{₤}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: {p€}"
msgstr "price: {p₤}"
Another example. Now, we want to add timestamps. In this case, we
decide for modifier names in C<\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
=head3 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: {p€%9s}\n", p => $p; # price: ␣␣␣123.45
printi ">{t T%10s}<", t => $now; # >␣␣12:59:17<
printp "price: %9{€}s\n", $p; # price: ␣␣␣123.45
printp ">%10{T}s<", $now; # >␣␣12:59:17<
=head2 Compared to other modules on CPAN
There are a quite a number of modules on CPAN which extend the functionality
of C<printf()>. To name a few:
L<String::Format|http://search.cpan.org/~darren/String-Format>,
L<String::Errf|http://http://search.cpan.org/~rjbs/String-Errf>,
L<String::Formatter|http://http://search.cpan.org/~rjbs/String-Formatter>,
L<Text::Sprintf::Named|http://search.cpan.org/~shlomif/Text-Sprintf-Named>,
L<Acme::StringFormat|http://search.cpan.org/~gfuji/Acme-StringFormat>,
L<Text::sprintf|http://search.cpan.org/~sharyanto/Text-sprintfn>,
L<Log::Sprintf|http://search.cpan.org/~frew/Log-Sprintf>, and
L<String::Sprintf|http://search.cpan.org/~bartl/String-Sprintf>.
They are all slightly different.
When the C<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 C<String::Print> cleanly
separates the roles of serializers, modifiers, and conversions.
C<String::Print> is nicely integrated with Log::Report.
=head1 SEE ALSO
This module is part of String-Print distribution version 0.15,
built on March 14, 2014. Website: F<http://perl.overmeer.net/log-report/>
=head1 LICENSE
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 F<http://www.perl.com/perl/misc/Artistic.html>
|