.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "String::Print 3pm" .TH String::Print 3pm "2020-03-07" "perl v5.30.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" String::Print \- printf alternative .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& ### Functional interface \& \& use String::Print; # simpelest way \& use String::Print qw/printi printp/, %config; \& printi \*(Aqage {years}\*(Aq, years => 12; \& \& # interpolation of arrays and hashes (serializers) \& printi \*(Aqprice\-list: {prices}\*(Aq, prices => \e@p, _join => "+"; \& printi \*(Aqdump: {c}\*(Aq, c => \e%config; \& \& # same with positional parameters \& printp \*(Aqage %d", 12; \& printp \*(Aqprice\-list: %.2f\*(Aq, \e@prices; \& printp \*(Aqdump: %s\*(Aq, \e%settings; \& \& # modifiers \& printi \*(Aqprice: {price%.2f}\*(Aq, price => 3.14*VAT*EURO; \& \& # [0.91] more complex interpolation names \& printi \*(Aqfilename: {c.filename}\*(Aq, c => \e%config; \& printi \*(Aqusername: {user.name}\*(Aq, user => $user_object; \& printi \*(Aqprice: {product.price €}\*(Aq, product => $db\->product(3); \& \& ### Object Oriented interface \& \& use String::Print \*(Aqoo\*(Aq; # import nothing \& my $f = String::Print\->new(%config); \& $f\->printi(\*(Aqage {years}\*(Aq, years => 12); \& $f\->printp(\*(Aqage %d\*(Aq, 12); \& \& ### via Log::Report\*(Aqs _\|_* functions (optional translation) \& \& use Log::Report; # or Log::Report::Optional \& print _\|_x"age {years}", years => 12; \& \& ### via Log::Report::Template (Template Toolkit extension) \& \& [% SET name = \*(AqJohn Doe\*(Aq %] \& [% loc("Dear {name},") %] # includes translation .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" This module inserts values into (format) strings. It provides \f(CW\*(C`printf\*(C'\fR and \f(CW\*(C`sprintf\*(C'\fR alternatives via both an object oriented and a functional interface. .PP Read in the \*(L"\s-1DETAILS\*(R"\s0 chapter below, why this module provides a better alternative for \f(CW\*(C`printf()\*(C'\fR. Also, some extended \fBexamples\fR can be found down there. Take a look at them first, when you start using this module! .SH "METHODS" .IX Header "METHODS" .SS "The Object Oriented interface" .IX Subsection "The Object Oriented interface" See functions \fBprinti()\fR, \fBsprinti()\fR, \fBprintp()\fR, and \fBsprintp()\fR: you can also call them as method. .PP .Vb 3 \& use String::Print \*(Aqoo\*(Aq; \& my $f = String::Print\->new(%config); \& $f\->printi($format, @params); \& \& # exactly the same functionality: \& use String::Print \*(Aqprinti\*(Aq, %config; \& printi $format, @params; .Ve .PP 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. .PP \fIConstructors\fR .IX Subsection "Constructors" .IP "String::Print\->\fBnew\fR(%options)" 4 .IX Item "String::Print->new(%options)" .Vb 5 \& \-Option \-\-Default \& encode_for undef \& missing_key \& modifiers [ qr/^%\eS+/ = \e&format_printf]> \& serializers .Ve .RS 4 .IP "encode_for => HASH|'\s-1HTML\s0'" 2 .IX Item "encode_for => HASH|'HTML'" [0.91] The format string and the inserted values will get encoded according to some syntax rules. For instance, \f(CW\*(C`encode_entities()\*(C'\fR of HTML::Entities when you specify the predefined string \f(CW\*(C`HTML\*(C'\fR. See \fBencodeFor()\fR. .IP "missing_key => \s-1CODE\s0" 2 .IX Item "missing_key => CODE" [0.91] During interpolation, it may be discovered that a key is missing from the parameter list. In that case, a warning is produced and \f(CW\*(C`undef\*(C'\fR inserted. May can overrule that behavior. .IP "modifiers => \s-1ARRAY\s0" 2 .IX 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 \f(CW\*(C`print[ip]\*(C'\fR itself. .IP "serializers => HASH|ARRAY" 2 .IX Item "serializers => HASH|ARRAY" How to serialize data elements. .RE .RS 4 .Sp example: .Sp .Vb 5 \& my $f = String::Print\->new \& ( modifiers => [ EUR => sub {sprintf "%5.2f e", $_[0]} ] \& , serializers => [ UNDEF => sub {\*(Aq\-\*(Aq} ] \& , encode_for => \*(AqHTML\*(Aq \& ); \& \& $f\->printi("price: {p EUR}", p => 3.1415); # price: ␣␣3.14 e \& $f\->printi("count: {c}", c => undef); # count: \- .Ve .RE .PP \fIAttributes\fR .IX Subsection "Attributes" .ie n .IP "$obj\->\fBaddModifiers\fR(\s-1PAIRS\s0)" 4 .el .IP "\f(CW$obj\fR\->\fBaddModifiers\fR(\s-1PAIRS\s0)" 4 .IX Item "$obj->addModifiers(PAIRS)" The \s-1PAIRS\s0 are a combination of an selector and a \s-1CODE\s0 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 \s-1ARRAY\s0 of modifiers per \f(CW\*(C`print\*(C'\fR. .Sp See section \*(L"Interpolation: Modifiers\*(R" about the details. .ie n .IP "$obj\->\fBencodeFor\fR(HASH|undef|($predefined, %overrule))" 4 .el .IP "\f(CW$obj\fR\->\fBencodeFor\fR(HASH|undef|($predefined, \f(CW%overrule\fR))" 4 .IX Item "$obj->encodeFor(HASH|undef|($predefined, %overrule))" [0.91] Enable/define the output encoding. Read section \*(L"Output encoding\*(R" about the details. .PP \fIPrinting\fR .IX Subsection "Printing" .PP The following are provided as method and as function. You find their explanation further down on this page. .PP \&\f(CW$obj\fR\->\fBprinti\fR([$fh], \f(CW$format\fR, PAIRS|HASH); .PP \&\f(CW$obj\fR\->\fBprintp\fR([$fh], \f(CW$format\fR, PAIRS|HASH); .PP \&\f(CW$obj\fR\->\fBsprinti\fR($format, PAIRS|HASH); .PP \&\f(CW$obj\fR\->\fBsprintp\fR($format, \s-1LIST, PAIRS\s0); .SH "FUNCTIONS" .IX Header "FUNCTIONS" The functional interface creates a hidden object. You may import any of these functions explicitly, or all together by not specifying the names. .PP \&\fB. Example\fR .PP .Vb 2 \& use String::Print; # all \& use String::Print \*(Aqsprinti\*(Aq; # only sprinti \& \& use String::Print \*(Aqprinti\*(Aq # only printi \& , modifiers => [ EUR => sub {sprintf "%5.2f e", $_[0]} ] \& , serializers => [ UNDEF => sub {\*(Aq\-\*(Aq} ]; \& \& printi "price: {p EUR}", p => 3.1415; # price: ␣␣3.14 e \& printi "count: {c}", c => undef; # count: \- .Ve .ie n .IP "\fBprinti\fR( [$fh], $format, PAIRS|HASH )" 4 .el .IP "\fBprinti\fR( [$fh], \f(CW$format\fR, PAIRS|HASH )" 4 .IX Item "printi( [$fh], $format, PAIRS|HASH )" Calls \fBsprinti()\fR to fill the data in \s-1PAIRS\s0 or \s-1HASH\s0 in \f(CW$format\fR, and then sends it to the \f(CW$fh\fR (by default the selected file) .Sp .Vb 2 \& open my $fh, \*(Aq>\*(Aq, $file; \& printi $fh, ... \& \& printi \e*STDERR, ... .Ve .ie n .IP "\fBprintp\fR( [$fh], $format, PAIRS|HASH )" 4 .el .IP "\fBprintp\fR( [$fh], \f(CW$format\fR, PAIRS|HASH )" 4 .IX Item "printp( [$fh], $format, PAIRS|HASH )" Calls \fBsprintp()\fR to fill the data in \s-1PAIRS\s0 or \s-1HASH\s0 in \f(CW$format\fR, and then sends it to the \f(CW$fh\fR (by default the selected file) .IP "\fBsprinti\fR($format, PAIRS|HASH|OBJECT)" 4 .IX Item "sprinti($format, PAIRS|HASH|OBJECT)" The \f(CW$format\fR refers to some string, maybe the result of a translation. .Sp The \s-1PAIRS\s0 (which may be passed as \s-1LIST, HASH,\s0 or blessed \s-1HASH\s0) contains a mixture of special and normal variables to be filled in. The names of the special variables (the options) start with an underscore (\f(CW\*(C`_\*(C'\fR). .Sp .Vb 5 \& \-Option \-\-Default \& _append undef \& _count undef \& _join \*(Aq, \*(Aq \& _prepend undef .Ve .RS 4 .IP "_append => STRING|OBJECT" 2 .IX Item "_append => STRING|OBJECT" Text as \s-1STRING\s0 appended after \f(CW$format\fR, without interpolation. .IP "_count => \s-1INTEGER\s0" 2 .IX 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. .IP "_join => \s-1STRING\s0" 2 .IX Item "_join => STRING" Which \s-1STRING\s0 to use when an \s-1ARRAY\s0 is being filled-in as parameter. .IP "_prepend => STRING|OBJECT" 2 .IX Item "_prepend => STRING|OBJECT" Text as \s-1STRING\s0 prepended before \f(CW$format\fR, without interpolation. This may also be an \s-1OBJECT\s0 which gets stringified, but variables not filled-in. .RE .RS 4 .RE .IP "\fBsprintp\fR($format, \s-1LIST, PAIRS\s0)" 4 .IX Item "sprintp($format, LIST, PAIRS)" Where \fBsprinti()\fR uses named parameters \-\-especially useful when the strings need translation\*(-- this function stays close to the standard \&\f(CW\*(C`sprintf()\*(C'\fR. All features of \s-1POSIX\s0 formats are supported. This should say enough: you can use \f(CW\*(C`%3$0#5.*d\*(C'\fR, if you like. .Sp It may be useful to know that the positional \f(CW$format\fR is rewritten and then fed into \fBsprinti()\fR. \fBBe careful\fR with the length of the \s-1LIST:\s0 superfluous parameter \s-1PAIRS\s0 are passed along to \f(CW\*(C`sprinti()\*(C'\fR, and should only contain \*(L"specials\*(R": parameter names which start with '_'. .Sp example: of the rewrite .Sp .Vb 3 \& # positional parameters \& my $x = sprintp "dumpfiles: %s\en", \e@dumpfiles \& , _join => \*(Aq:\*(Aq; \& \& # is rewritten into, and then processed as \& my $x = sprinti "dumpfiles: {_1}\en" \& , _1 => \e@dumpfiles, _join => \*(Aq:\*(Aq; .Ve .SH "DETAILS" .IX Header "DETAILS" .ie n .SS "Why use ""printi()"", not ""printf()""?" .el .SS "Why use \f(CWprinti()\fP, not \f(CWprintf()\fP?" .IX Subsection "Why use printi(), not printf()?" The \f(CW\*(C`printf()\*(C'\fR function is provided by Perl's \s-1CORE\s0; you do not need to install any module to use it. Why would you use consider using this module? .IP "translating" 4 .IX Item "translating" \&\f(CW\*(C`printf()\*(C'\fR uses positional parameters, where \fBprinti()\fR 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 \&\fBprintp()\fR .IP "pluggable serializers" 4 .IX Item "pluggable serializers" \&\f(CW\*(C`printi()\*(C'\fR supports serialization for specific data-types: how to interpolate \f(CW\*(C`undef\*(C'\fR, HASHes, etc. .IP "pluggable modifiers" 4 .IX Item "pluggable modifiers" Especially useful in context of translations, the \s-1FORMAT\s0 string may contain (language specific) helpers to insert the values correctly. .IP "correct use of utf8" 4 .IX Item "correct use of utf8" Sized string formatting in \f(CW\*(C`printf()\*(C'\fR is broken: it takes your string as bytes, not Perl strings (which may be utf8). In unicode, one \&\*(L"character\*(R" may use many bytes. Also, some characters are displayed double wide, for instance in Chinese. The \fBprinti()\fR implementation will use Unicode::GCString for correct behavior. .IP "automatic output encoding (for \s-1HTML\s0)" 4 .IX Item "automatic output encoding (for HTML)" You can globally declare that all produced strings must be encoded in a certain format, for instance that \s-1HTML\s0 entities should be encoded. .SS "Four components" .IX Subsection "Four components" To fill-in a \s-1FORMAT,\s0 four clearly separated components play a role: .IP "1. modifiers" 4 .IX Item "1. modifiers" How to change the provided values, for instance to hide locale differences. .IP "2. serializer" 4 .IX Item "2. serializer" How to represent (the modified) the values correctly, for instance \f(CW\*(C`undef\*(C'\fR and ARRAYs. .IP "3. conversion" 4 .IX Item "3. conversion" The standard \s-1UNIX\s0 format rules, like \f(CW%d\fR. One conversion rule has been added 'S', which provides unicode correct behavior. .IP "4. encoding" 4 .IX Item "4. encoding" Prepare the output for a certain syntax, like \s-1HTML.\s0 .PP Simplified: .PP .Vb 2 \& # sprinti() replaces "{$key$modifiers$conversion}" by \& $encode\->($format\->($serializer\->($modifiers\->($args{$key})))) \& \& # sprintp() replaces "%pos{$modifiers}$conversion" by \& $encode\->($format\->($serializer\->($modifiers\->($arg[$pos])))) .Ve .PP Example: .PP .Vb 5 \& #XXX Your manual\-page reader may not support the unicode used \& #XXX in the examples below. \& printi "price: {price € %\-10s}", price => $cost; \& printi "price: {price € %\-10s}", { price => $cost }; \& printp "price: %\-10{€}s", $cost; \& \& $value = $cost (in €) \& $modifier = convert € to local currency £ \& $serializer = show float as string \& $format = column width %\-10s \& $encode = £ into £ # when encodingFor(\*(AqHTML\*(Aq) .Ve .SS "Interpolation: keys" .IX Subsection "Interpolation: keys" A key is a bareword (like a variable name) or a list of barewords separated by dots (no blanks!) .PP \&\fBPlease\fR use explanatory key names, to help the translation process once you need that (in the future). .PP \fISimple keys\fR .IX Subsection "Simple keys" .PP A simple key directly refers to a named parameter of the function or method: .PP .Vb 1 \& printi "Username: {name}", name => \*(AqJohn\*(Aq; .Ve .PP You may also pass them as \s-1HASH\s0 or \s-1CODE:\s0 .PP .Vb 4 \& printi "Username: {name}", { name => \*(AqJohn\*(Aq }; \& printi "Username: {name}", name => sub { \*(AqJohn\*(Aq }; \& printi "Username: {name}", { name => sub { \*(AqJohn\*(Aq } }; \& printi "Username: {name}", name => sub { sub {\*(AqJohn\*(Aq} }; .Ve .PP The smartness of pre-processing \s-1CODE\s0 is part of serialization. .PP \fIComplex keys\fR .IX Subsection "Complex keys" .PP [0.91] In the previous section, we kept our addressing it simple: let's change that now. Two alternatives for the same: .PP .Vb 3 \& my $user = { name => \*(AqJohn\*(Aq }; \& printi "Username: {name}", name => $user\->{name}; # simple key \& printi "Username: {user.name}", user => $user; # complex key .Ve .PP The way these complex keys work, is close to the flexibility of template toolkit: the only thing you cannot do, is passing parameters to called \s-1CODE.\s0 .PP You can pass a parameter name as \s-1HASH,\s0 which contains values. This may even be nested into multiple levels. You may also pass objects, class (package names), and code references. .PP In above case of \f(CW\*(C`user.name\*(C'\fR, when \f(CW\*(C`user\*(C'\fR is a \s-1HASH\s0 it will take the value which belongs to the key \f(CW\*(C`name\*(C'\fR. When \f(CW\*(C`user\*(C'\fR is a \s-1CODE,\s0 it will run code to get a value. When \f(CW\*(C`user\*(C'\fR is an object, the method \f(CW\*(C`name\*(C'\fR is called to get a value back. When \f(CW\*(C`user\*(C'\fR is a class name, the \f(CW\*(C`name\*(C'\fR refers to an instance method on that class. .PP More examples which do work: .PP .Vb 2 \& # when name is a column in the database query result \& printi "Username: {user.name}", user => $sth\->fetchrow_hashref; \& \& # call a sub which does the database query, returning a HASH \& printi "Username: {user.name}", user => sub { $db\->getUser(\*(AqJohn\*(Aq) }; \& \& # using an instance method (object) \& { package User; \& sub new { bless { myname => $_[1] }, $_[0] } \& sub name { $_[0]\->{myname} } \& } \& my $user = User\->new(\*(AqJohn\*(Aq); \& printi "Username: {user.name}", user => $user; \& \& # using a class method \& sub User::count { 42 } \& printi "Username: {user.count}", user => \*(AqUser\*(Aq; \& \& # nesting, mixing \& printi "Complain to {product.factory.address}", product => $p; \& \& # mixed, here CODE, HASH, and Object \& printi "Username: {document.author.name}", document => sub { \& return +{ author => User\->new(\*(AqJohn\*(Aq) } \& }; .Ve .PP Limitation: you cannot pass arguments to \s-1CODE\s0 calls. .SS "Interpolation: Serialization" .IX Subsection "Interpolation: Serialization" The 'interpolation' functions have named \s-1VARIABLES\s0 to be filled-in, but also additional \s-1OPTIONS.\s0 To distinguish between the \s-1OPTIONS\s0 and \s-1VARIABLES\s0 (both a list of key-value pairs), the keys of the \s-1OPTIONS\s0 start with an underscore \f(CW\*(C`_\*(C'\fR. 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 \s-1OPTION\s0 values in your strings. .PP 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 \f(CW\*(C`undef\*(C'\fR. .IP "strings" 4 .IX Item "strings" Simple scalar values are interpolated \*(L"as is\*(R" .IP "\s-1CODE\s0" 4 .IX Item "CODE" When a value is passed as \s-1CODE\s0 reference, that function will get called to return the value to be filled in. For interpolating, the following rules apply: .IP "\s-1SCALAR\s0" 4 .IX Item "SCALAR" Takes the value where the scalar reference points to. .IP "\s-1ARRAY\s0" 4 .IX Item "ARRAY" All members will be interpolated with \f(CW\*(C`,␣\*(C'\fR between the elements. Alternatively (maybe nicer), you can pass an interpolation parameter via the \f(CW\*(C`_join\*(C'\fR \s-1OPTION.\s0 .Sp .Vb 1 \& printi "matching files: {files}", files => \e@files, _join => \*(Aq, \*(Aq .Ve .IP "\s-1HASH\s0" 4 .IX Item "HASH" By default, HASHes are interpolated with sorted keys, .Sp .Vb 1 \& $key => $value, $key2 => $value2, ... .Ve .Sp There is no quoting on the keys or values (yet). Usually, this will produce an ugly result anyway. .IP "Objects" 4 .IX Item "Objects" With the \f(CW\*(C`serialization\*(C'\fR parameter, you can overrule the interpolation of above defaults, but also add rules for your own objects. By default, objects get stringified. .Sp .Vb 1 \& serialization => [ $myclass => \e&name_in_reverse ] \& \& sub name_in_reverse($$$) \& { my ($formatter, $object, $args) = @_; \& # the $args are all parameters to be filled\-in \& scalar reverse $object\->name; \& } .Ve .SS "Interpolation: Modifiers" .IX Subsection "Interpolation: Modifiers" Modifiers are used to change the value to be inserted, before the characters get interpolated in the line. This is a powerful simplification. Let's discuss this with an example. .PP In traditional (gnu) gettext, you would write: .PP .Vb 1 \& printf(gettext("approx pi: %.6f\en"), PI); .Ve .PP to get \s-1PI\s0 printed with six digits in the fragment. Locale::TextDomain has two ways to achieve that: .PP .Vb 2 \& printf _\|_"approx pi: %.6f\en", PI; \& print _\|_x"approx pi: {approx}\en", approx => sprintf("%.6f", PI); .Ve .PP 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 string to be translated differs between the two examples. .PP With \f(CW\*(C`Log::Report\*(C'\fR, above syntaxes do work as well, but you can also do: .PP .Vb 2 \& # with optional translations \& print _\|_x"approx pi: {pi%.6f}\en", pi => PI; .Ve .PP The base for \f(CW\*(C`_\|_x()\*(C'\fR is the \fBprinti()\fR provided by this module. Internally, it will call \f(CW\*(C`printi\*(C'\fR to fill-in parameters: .PP .Vb 1 \& printi "approx pi: {pi%.6f}\en", pi => PI; .Ve .PP Another example: .PP .Vb 3 \& printi "{perms} {links%2d} {user%\-8s} {size%10d} {fn}\en", \& perms => \*(Aq\-rw\-r\-\-r\-\-\*(Aq, links => 7, user => \*(Aqme\*(Aq, \& size => 12345, fn => $filename; .Ve .PP An additional advantage (when you use translation) is the fact that not all languages produce comparable length strings. Now, the translators can change the format, such that the layout of tables is optimal for their language. .PP Above example in \fBprintp()\fR syntax, shorter but less maintainable: .PP .Vb 2 \& printp "%s %2d %\-8s 10d %s\en", \& \*(Aq\-rw\-r\-\-r\-\-\*(Aq, 7, \*(Aqme\*(Aq, 12345, $filename; .Ve .SS "Interpolation: default modifiers" .IX Subsection "Interpolation: default modifiers" \fIDefault modifier: \s-1POSIX\s0 format\fR .IX Subsection "Default modifier: POSIX format" .PP As shown in the examples above, you can specify a format. This can, for instance, help you with rounding or columns: .PP .Vb 3 \& printp "π = {pi%.3f}", pi => 3.1415; \& printp "weight is {kilogram%d}", kilogram => 127*OUNCE_PER_KILO; \& printp "{filename%\-20.20s}\en", filename => $fn; .Ve .PP \- improvements on \s-1POSIX\s0 format .IX Subsection "- improvements on POSIX format" .PP The \s-1POSIX\s0 \f(CW\*(C`printf()\*(C'\fR does not handle unicode strings. Perl does understand that the 's' modifier may need to insert utf8 so does not count bytes but characters. \f(CW\*(C`printi()\*(C'\fR does not use characters but \&\*(L"grapheme clusters\*(R" via Unicode::GCString. Now, also composed characters do work correctly. .PP Additionally, you can use the \fBnew 'S' conversion\fR 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'. .PP .Vb 2 \& # name right aligned, commas on same position, always \& printp "name: {name%20S},\en", name => $some_chinese; .Ve .PP \fIDefault modifier: \s-1BYTES\s0\fR .IX Subsection "Default modifier: BYTES" .PP [0.91] Too often, you have to translate a (file) size into humanly readible format. The \f(CW\*(C`BYTES\*(C'\fR modifier simplifies this a lot: .PP .Vb 1 \& printp "{size BYTES} {fn}\en", fn => $fn, size => \-s $fn; .Ve .PP The output will always be 6 characters. Examples are \*(L"999 B\*(R", \*(L"1.2 kB\*(R", and \*(L" 27 \s-1MB\*(R".\s0 .PP \fIDefault modifiers: \s-1YEAR, DATE, TIME, DT,\s0 and \s-1\f(BIDT\s0()\fI\fR .IX Subsection "Default modifiers: YEAR, DATE, TIME, DT, and DT()" .PP [0.91] A set of modifiers help displaying dates and times. They are a little flexible in values they accept, but do not expect miracles: when it get harder, you will need to process it yourself. .PP The actual treatment of a time value depends on the value: three different situations: .IP "1. numeric" 4 .IX Item "1. numeric" A pure numeric value is considered \*(L"seconds since epoch\*(R", unless it is smaller than 21000000, in which case it is taken as date without separators. .IP "2. date format without time-zone" 4 .IX Item "2. date format without time-zone" The same formats are understood as in the next option, but without time-zone information. The date is processed as text as if in the local time zone, and the output in the local time-zone. .IP "3. date format with time-zone" 4 .IX Item "3. date format with time-zone" By far not all possible date formats are supported, just a few common versions, like .Sp .Vb 7 \& 2017\-06\-27 10:04:15 +02:00 \& 2017\-06\-27 17:34:28.571491+02 # psql timestamp with zone \& 20170627100415+2 \& 2017\-06\-27T10:04:15Z # iso 8601 \& 20170627 # only for YEAR and DATE \& 2017\-6\-1 # only for YEAR and DATE \& 12:34 # only for TIME .Ve .Sp The meaning of 05\-04\-2017 is unclear, so not supported. Milliseconds get ignored. .Sp When the provided value has a timezone indication, it will get converted into the local timezone of the observer. .PP The output of \f(CW\*(C`YEAR\*(C'\fR is in format '\s-1YYYY\s0', for \f(CW\*(C`DATE\*(C'\fR it will always be \&'\s-1YYYY\-MM\-DD\s0', where \f(CW\*(C`TIME\*(C'\fR produces 'HH:mm:ss'. .PP The short form \f(CW\*(C`DT\*(C'\fR is an alias for \f(CW\*(C`DT(FT)\*(C'\fR. The \s-1DT\s0 modifier can produce different formats: .PP .Vb 5 \& DT(ASC) : %a %b %e %T %Y asctime output \& DT(FT) : %F %T YYYY\-MM\-DD HH:mm:ss \& DT(ISO) : %FT%T%z iso8601 \& DT(RFC822) : %a, %d %b %y %T %z email old \& DT(RFC2822) : %a, %d %b %Y %T %z email newer .Ve .PP You may suggest additional formats, or add your own modifier. .PP \fIDefault modifiers: //word, //\*(L"string\*(R", //'string'\fR .IX Subsection "Default modifiers: //word, //string, //'string'" .PP [0.91] By default, an undefined value is shown as text 'undef'. Empty strings are shown as nothing. This may not be nice. You may want to be more specific when a value is missing. .PP .Vb 3 \& "visitors: {count //0}" \& "published: {date DT//\*(Aqnot yet\*(Aq}" \& "copyright: {year//2017 YEAR} .Ve .PP Modifiers will usually return \f(CW\*(C`undef\*(C'\fR when they are called with an undefined or empty value. By the right order of '//', you may product different kinds of output: .PP .Vb 2 \& "price: {price//5 EUR}" \& "price: {price EUR//unknown}" .Ve .PP \fIPrivate modifiers\fR .IX Subsection "Private modifiers" .PP You may pass your own modifiers. A modifier consists of a selector and a \s-1CODE,\s0 which is called when the selector matches. The selector is either a string or a regular expression. .PP .Vb 4 \& # in Object Oriented syntax: \& my $f = String::Print\->new \& ( modifiers => [ qr/[€₤]/ => \e&money ] \& ); \& \& # in function syntax: \& use String::Print \*(Aqprinti\*(Aq, \*(Aqsprinti\*(Aq \& , modifiers => [ qr/[€₤]/ => \e&money ]; \& \& # the implementation: \& sub money$$$$) \& { my ($formatter, $modif, $value, $args) = @_; \& \& $modif eq \*(Aq€\*(Aq ? sprintf("%.2f EUR", $value+0.0001) \& : $modif eq \*(Aq₤\*(Aq ? sprintf("%.2f GBP", $value/1.16+0.0001) \& : \*(AqERROR\*(Aq; \& } .Ve .PP Using \fBprintp()\fR makes it a little shorter, but will become quite complex when there are more parameter in one string. .PP .Vb 2 \& 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 .Ve .PP This is very useful in the translation context, where the translator can specify abstract formatting rules. As example, see the (\s-1GNU\s0) gettext files, in the translation table for Dutch into English. The translator tells us which currency to use in the display. .PP .Vb 2 \& msgid "kostprijs: {p€}" \& msgstr "price: {p₤}" .Ve .PP Another example. Now, we want to add timestamps. In this case, we decide for modifier names in \f(CW\*(C`\ew\*(C'\fR, so we need a blank to separate the parameter from the modifer. .PP \fIModifiers: stacking\fR .IX Subsection "Modifiers: stacking" .PP 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. .PP The modifiers are called in order: .PP .Vb 2 \& printi "price: {p€%9s}\en", p => $p; # price: ␣␣␣123.45 \& printi ">{t T%10s}<", t => $now; # >␣␣12:59:17< \& \& printp "price: %9{€}s\en", $p; # price: ␣␣␣123.45 \& printp ">%10{T}s<", $now; # >␣␣12:59:17< .Ve .SS "Output encoding" .IX Subsection "Output encoding" [0.91] This module is also used by Log::Report::Template, which is used to insert (translated) strings with parameters into \s-1HTML\s0 templates. You can imagine that some of the parameter may need to be encoded to \&\s-1HTML\s0 in the template, and other not. .PP \fIexample with Log::Report::Template\fR .IX Subsection "example with Log::Report::Template" .PP In pure Template Toolkit, you would write .PP .Vb 4 \& # in your TT\-template \&
Username: [% username | html %]
\& # in your code \& username => $user\->name, .Ve .PP With plain String::Print with output encoding enabled, you can do: .PP .Vb 6 \& # in your TT\-template \&
[% show_username %]
\& # in your code with encodeFor(\*(AqHTML\*(Aq) \& show_username => printi("Username: {user}", user => $user\->name), \& # or \& show_username => printp("Username: %s", $user\->name), .Ve .PP That does not look very efficient, however it changes for the good when this is combined with Log::Report::Lexicon (translations) You can either do: .PP .Vb 4 \& # in your TT\-template \&
[% show_username %]
\& # in your code with encodeFor(\*(AqHTML\*(Aq) \& show_username => _\|_x("Username: {user}", user => $user\->name), .Ve .PP Shorter: .PP .Vb 4 \& # in your TT\-template with encodeFor(\*(AqHTML\*(Aq) \&
[% loc("Username: {user}", user => username) %]
\& # in your code \& username => $user\->name, .Ve .PP Even shorter: .PP .Vb 4 \& # in your TT\-template with encodeFor(\*(AqHTML\*(Aq) \&
[% loc("Username: {user.name}", user => userobj) %]
\& # in your code \& userobj => $user, .Ve .PP Shortest: .PP .Vb 4 \& # in your TT\-template with encodeFor(\*(AqHTML\*(Aq) \&
[% loc("Username: {user.name}") %]
\& # in your code \& user => $user, .Ve .PP Shorter that the original, and translations for free! More examples in Log::Report::Template. .PP \fIOutput encoding exclusion\fR .IX Subsection "Output encoding exclusion" .PP In some cases, the data which is inserted is already encoded in the output syntax. For instance, you already have \s-1HTML\s0 to be included. .PP The default exclusion rule for \s-1HTML\s0 output is \f(CW\*(C`qr/html$/i\*(C'\fR, which means that all inserted named parameters, where the name ends on \f(CW\*(C`html\*(C'\fR will not get html-entity encoded. .PP This will work by default: .PP .Vb 3 \& # with encodeFor(\*(AqHTML\*(Aq) \& printp "Me & Co: {name}, {description_html}", \& name => \*(AqRené\*(Aq, description_html => $descr; .Ve .PP This may result in: .PP .Vb 1 \& Me & Co: René, new member .Ve .PP Better not to have \s-1HTML\s0 in your program: leave it to the template. But in some cases, you have no choice. .SS "Compared to other modules on \s-1CPAN\s0" .IX Subsection "Compared to other modules on CPAN" There are a quite a number of modules on \s-1CPAN\s0 which extend the functionality of \f(CW\*(C`printf()\*(C'\fR. To name a few: String::Format , String::Errf , String::Formatter , Text::Sprintf::Named , Acme::StringFormat , Text::sprintf , Log::Sprintf , and String::Sprintf . They are all slightly different. .PP When the \f(CW\*(C`String::Print\*(C'\fR 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 \f(CW\*(C`String::Print\*(C'\fR cleanly separates the roles of serializers, modifiers, and conversions. .PP \&\f(CW\*(C`String::Print\*(C'\fR is nicely integrated with Log::Report. .SH "SEE ALSO" .IX Header "SEE ALSO" This module is part of String-Print distribution version 0.94, built on March 01, 2020. Website: \fIhttp://perl.overmeer.net/CPAN/\fR .SH "LICENSE" .IX Header "LICENSE" Copyrights 2016\-2020 by [Mark Overmeer ]. For other contributors see ChangeLog. .PP This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See \fIhttp://dev.perl.org/licenses/\fR