String::Print(3pm)
โจ NAME โจ
String::Print(3pm) โ User Contributed Perl Documentation. String::Print - printf alternative. ๐
๐ SYNOPSIS ๐
okay bestie, here's the whole vibe, copy-paste energy:
### Functional interface
use String::Print; # simpelest way
use String::Print qw/printi printp/, %config;
printi 'age {years}', years => 12; # to STDOUT
my $s = sprinti 'age {years}', years => 12; # in variable
# interpolation of arrays and hashes (serializers)
printi 'price-list: {prices}', prices => \@p, _join => "+";
printi 'dump: {c}', c => \%data;
# same with positional parameters
printp 'age %d", 12;
printp 'price-list: %.2f', \@prices;
printp 'dump: %s', \%settings;
my $s = sprintp 'age %d", 12;
# modifiers
printi 'price: {price%.2f}', price => 3.14 * EURO;
# [0.91] more complex interpolation names
printi 'filename: {c.filename}', c => \%data;
printi 'username: {user.name}', user => $user_object;
printi 'price: {product.price โฌ}', product => $db->product(3);
### Object Oriented interface
use String::Print 'oo', %config; # import no functions
my $f = String::Print->new(%config);
$f->printi('age {years}', years => 12);
$f->printp('age %d', 12);
my $s = $f->sprinti('age {y}', y => 12);
my $s = $f->sprintp('age %d', 12);
### via Log::Report's __* 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 = 'John Doe' %]
[% loc("Dear {name},") %] # includes translation
๐ DESCRIPTION ๐
okay so String::Print inserts values into (format) strings. It gives you printf() and sprintf() alternatives through both an object oriented and a functional interface. ๐
Go read the "DETAILS" chapter below for why this module provides a better alternative for printf(). There are also some extended examples down there. Take a look at them first when you start using this module! ๐ซถ
๐ METHODS ๐
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. โจ
๐ ๏ธ Constructors ๐ ๏ธ
When you use this package with functions, then you do not call the constructor explicitly. In that case, these new() parameters are added to the <use String::Print> line.
$class->new(%options)
The %options of the constructure configure processing options.
defaults=>\%mapโ default:see modifier docs. [1.00] change the defaults for some modifiers. This is a%mapof modifier name to HASH with modifier specific settings. ๐encode_for=>\%rules|'HTML'โ default:undef. [0.91] The format string and the inserted values will get encoded according to some%rules. Functionencode_entities()provided byHTML::Entitiesis used when you specify the predefined string"HTML". SeeencodeFor()and "Output encoding". ๐missing_key=>CODEโ default:<warning>. [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"undef"inserted. May can overrule that behavior. ๐ญmodifiers=>ARRAYโ default:[ qr/^%\S+/ = \&format_printf]>. 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"print[ip]"itself. ๐ฅserializers=>HASH|ARRAYโ default:<useful defaults>. How to serialize data elements. ๐ง
ยป example:
my $f = String::Print->new(
modifiers => [ EUR => sub {sprintf "%5.2f e", $_[0]} ],
serializers => [ UNDEF => sub {'-'} ],
encode_for => 'HTML',
);
$f->printi("price: {p EUR}", p => 3.1415); # price: โฃโฃ3.14 e
$f->printi("count: {c}", c => undef); # count: -
๐ Attributes ๐
$obj->addModifiers(PAIRS)โ The"PAIRS"are a combination of an selector and aCODEwhich 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 anARRAYof modifiers perprinti()orprintp().
See section "Interpolation: Modifiers" about the details. ๐ฆ
$obj->defaults($modifier)โ [1.00] Returns the current defaults for the$modifier.
ยป example: getting defaults for a modifier
my $def = $sp->defaults('EL');
say "Default max width is ", $def->{width};
$obj->encodeFor(\%settings|undef|($predefined, %overrule))โ [0.91] Enable/define the output encoding. The%settingscontain the"encoding"CODEand the tag name patterns to"exclude"from encoding. Output for"HTML"is$predefined, but you may%overruleits settings.
Read section "Output encoding" about the details. ๐ธ
$obj->setDefaults(\%defaults|@defaults)โ [1.00] Set the defaults for modifiers, either with aHASHwhere the key modifier name maps to aHASHof settings, or a list ofPAIRS.
When using the methods in OO style , you can change the defaults at any time. For functional style, the object is hidden.
ยป example: setting defaults
$sp->setDefaults(EL => {width => 30}, CHOP => {width => 10});
my %defs = (EL => {width => 30}, CHOP => {width => 10});
$sp->setDefaults(\%defs);
๐จ๏ธ Printing ๐จ๏ธ
The following are provided both as method and as function. The function version is explained further down on this page, because it reads a bit easier, but the object version is most flexible.
my $sp = String::Print->new;
$sp->printi([$fh], $format, %data|\%data); # see printi()
$sp->printp([$fh], $format, @params, %options); # see printp()
my $s = $sp->sprinti($format, %data|\%data); # see sprinti()
my $s = $sp->sprintp($format, @params, %options); # see sprintp()
ยป Example
use String::Print 'oo'; # do not import the functions
my $sp = String::Print->new(
modifiers => [ EUR => sub {sprintf "%5.2f e", $_[0]} ],
serializers => [ UNDEF => sub {'-'} ],
defaults => [ DT => { standard => 'ISO' } ],
);
$sp->printi("price: {p EUR}", p => 3.1415); # price: โฃโฃ3.14 e
$sp->printi("count: {c}", c => undef); # count: -
my $s = $sp->sprinti("price: {p EUR}", p => 7); # output in $s
โจ FUNCTIONS โจ
The functional interface creates a hidden String::Print object, which is reused in the whole active package. Seperate packages will use different hidden objects. ๐
You may import any of these functions explicitly, or all together by not specifying the names.
ยป Example
use String::Print; # all
use String::Print 'sprinti'; # only sprinti
use String::Print 'printi', # only printi
modifiers => [ EUR => sub {sprintf "%5.2f e", $_[0]} ],
serializers => [ UNDEF => sub {'-'} ],
defaults => [ DT => { standard => 'ISO' } ];
printi "price: {p EUR}", p => 3.1415; # price: โฃโฃ3.14 e
printi "count: {c}", c => undef; # count: -
my $s = sprinti "price: {p EUR}", p => 7; # output in $s
printi( [$fh], $format, %data|\%data )โ Callssprinti()to fill the%datainto$format, and then sends it to the$fh(by default the selected file handle).
open my $fh, '>:encoding(UTF-8)', $file;
printi $fh, ...
printi \*STDERR, ...
printp( [$fh], $format, @positionals, %options )โ Callssprintp()to fill the@positionalsin$format, and then sends it to the$fh(by default the selected file handle).sprinti($format, %data|\%data|OBJECT, %options)โ The$formatrefers to some string, maybe the result of a translation.
The %data (which may be passed as LIST, HASH, or blessed 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
_append=>STRING|OBJECTโ Text asSTRINGappended after$format, without interpolation._count=>INTEGERโ Result of the translation process: whenLog::Reportsubroutine__xnis are used for count-sensitive translation. Those function may add more specials to the parameter list._join=>STRINGโ WhichSTRINGto use when anARRAYis being filled-in as parameter._prepend=>STRING|OBJECTโ Text asSTRINGprepended before$format, without interpolation. This may also be an"OBJECT"which gets stringified, but variables not filled-in.
sprintp($format, @positionals, %options)โ Wheresprinti()uses named parameters --especially useful when the strings need translation-- this function stays close to the standardsprintf(). All features of POSIX formats are supported. This should say enough: you can use"%3$0#5.*d", if you like.
It may be useful to know that the positional $format is rewritten and then fed into sprinti(). Be careful with the length of the @positionals: superfluous parameter %options are passed along to sprinti(), and should only contain "specials": parameter names which start with '_'.
ยป example: of the rewrite
# positional parameters
my $x = sprintp "dumpfiles: %s\n", \@dumpfiles, _join => ':';
# is rewritten into, and then processed as
my $x = sprinti "dumpfiles: {_1}\n", _1 => \@dumpfiles, _join => ':';
๐ DETAILS ๐
Your manual-page reader may not support the unicode used in some of the examples below.
๐ค Why use printi() to replace printf()? ๐ค
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?
- translating โ
printf()uses positional parameters, whereprinti()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 ofprintp() - pluggable serializers โ
printi()ships serialization for specific data-types on purpose: how to interpolate"undef", HASHes, etc. ๐ - pluggable modifiers โ especially useful when translations are in the picture, the
FORMATstring may contain (language specific) helpers to insert the values correctly. ๐ - correct use of utf8 โ okay this one is a whole thing. Sized string formatting in
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. Theprinti()implementation will useUnicode::GCStringfor correct behavior. no cap, this is the glow-up ๐ฆ - automatic output encoding (for HTML) โ you can globally declare that all produced strings must be encoded in a certain format, for instance that HTML entities should be encoded. ๐
๐ธ Four components ๐ธ
To fill-in a FORMAT, four clearly separated components play a role, bestie:
- modifiers โ how to change the provided values, for instance to hide locale differences.
- serializer โ how to represent (the modified) the values correctly, for instance
"undef"and ARRAYs. - conversion โ the standard UNIX format rules, like
%d. One conversion rule has been added'S', which provides unicode correct behavior. - encoding โ prepare the output for a certain syntax, like HTML.
Simplified, because the full picture was giving chaos:
# sprinti() replaces "{$key$modifiers$conversion}" by
$encode->($format->($serializer->($modifiers->($args{$key}))))
# sprintp() replaces "%pos{$modifiers}$conversion" by
$encode->($format->($serializer->($modifiers->($arg[$pos]))))
Example time โจ
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('HTML')
๐ Interpolation: keys ๐
A key is a bareword (like a variable name) or a list of barewords separated by dots (no blanks!). ๐
Please use explanatory key names, to help the translation process once you need that (in the future). Future-you says thank you.
๐ Simple keys
A simple key directly refers to a named parameter of the function or method:
printi "Username: {name}", name => 'John';
You may also pass them as HASH or CODE:
printi "Username: {name}", { name => 'John' };
printi "Username: {name}", name => sub { 'John' };
printi "Username: {name}", { name => sub { 'John' } };
printi "Username: {name}", name => sub { sub {'John'} };
The smartness of pre-processing CODE is part of serialization. ๐ซ
๐ฆ Complex keys
[0.91] In the previous section, we kept our addressing it simple: let's change that now. Two alternatives for the same:
my $user = { name => 'John' };
printi "Username: {name}", name => $user->{name}; # simple key
printi "Username: {user.name}", user => $user; # complex key
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 CODE. ๐
You can pass a parameter name as HASH, which contains values. This may even be nested into multiple levels. You may also pass objects, class (package names), and code references.
In above case of "user.name", when "user" is a HASH it will take the value which belongs to the key "name". When "user" is a CODE, it will run code to get a value. When "user" is an object, the method "name" is called to get a value back. When "user" is a class name, the "name" refers to an instance method on that class.
More examples which do work (and they ate):
# 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('John') };
# using an instance method (object)
{ package User;
sub new { bless { myname => $_[1] }, $_[0] }
sub name { $_[0]->{myname} }
}
my $user = User->new('John');
printi "Username: {user.name}", user => $user;
# using a class method
sub User::count { 42 }
printi "Username: {user.count}", user => 'User';
# 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('John') }
};
Limitation: you cannot pass arguments to CODE calls. That's the rule, periodt.
๐ 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 "_". 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. ๐ค
Heads up: 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". ๐
- strings โ Simple scalar values are interpolated "as is" ๐
- 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:
- SCALAR โ Takes the value where the scalar reference points to.
- ARRAY โ All members will be interpolated with
",โฃ"between the elements. Alternatively (maybe nicer), you can pass an interpolation parameter via the"_join"OPTION.
printi "matching files: {files}", files => \@files, _join => ', '
- 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. ๐ญ
- Objects โ With the
"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;
}
๐ 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. Some useful modifiers are already provided by default. They are also good examples how to write your own. ๐
Let's discuss this with an example. In traditional (gnu) gettext, you would write:
printf(gettext("approx pi: %.6f\n"), PI);
to get PI printed with six digits in the fragment. Locale::TextDomain has two ways to achieve that:
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 string to be translated differs between the two examples.
With "Log::Report", above syntaxes do work as well, 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 (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. ๐โจ
Above example in printp() syntax, shorter but less maintainable:
printp "%s %2d %-8s 10d %s\n",
'-rw-r--r--', 7, 'me', 12345, $filename;
โจ Modifier: POSIX format starts with '%'
As shown in the examples above, you can specify a format. This can, for instance, help you with rounding or columns:
printp "ฯ = {pi%.3f}", pi => 3.1415;
printp "weight is {kilogram%d}", kilogram => 127*OUNCE_PER_KILO;
printp "{filename%-20.20s}\n", filename => $fn;
โจ POSIX modifier extension '%S'
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'.
# name right aligned, commas on same position, always
printp "name: {name%20S},\n", name => $some_chinese;
โจ POSIX modifier extensions '%d'
The full pattern is pretty complex: "%[+ -0]?[0-9]*[_,.]?d", POSIX format style with a few extra features. The middle (optional) digits tell the minimal size of the integer to be displayed. The optional character before it says: "+" will add a '+' sign when positive, 'blank' adds one blank before the digits when positive, a 0 pads left with zeros instead of blanks. Finally, a "-" means left-align padding blanks on the right.
[0.96] The last pattern is only useful when you print (big) decimals: add an underscore, comma, or dot on the thousands.
printi "{count%_d}\n", count => 1e9; # 1_000_000_000
printi "{count%,d}\n", count => 1e9; # 1,000,000,000
printi "{count%.d}\n", count => 1e9; # 1.000.000.000
printi "'{v%10.d}'", v => 10000; # ' 10.000';
printi "'{v%10_d}'", v => -10000; # ' -10_000';
printi "'{v%-10.d}'", v => 10000; # '10.000 ';
printi "'{v%-10.d}'", v => -10000; # '-10.000 ';
printi "'{v%+10,d}'", v => 10000; # ' +10,000';
printi "'{v% ,d}'", v => 10000; # ' 10,000';
printi "'{v% ,d}'", v => -10000; # '-10,000';
[1.00] You can set the default "FORMAT" separator:
use String::Print
defaults => [ FORMAT => { thousands => ',' } ];
# or
my $sp = String::Print->new(
defaults => { FORMAT => { thousands => ',' }},
);
# or
$sp->setDefaults(FORMAT => { thousands => ',' });
Okay so that's how you set FORMAT defaults, bestie. Now let's get into the modifiers that make your output literally iconic. ๐
Modifier: BYTES ๐พ
[0.91] Too often, you have to translate a (file) size into humanly readable format. The BYTES modifier simplifies this a lot โ and by a lot, I mean it's a whole vibe:
printp "{size BYTES} {fn}\n", fn => $fn, size => -s $fn;
The output will always be 5 characters. Examples are "999 B", "1.2kB", and " 27MB". No cap, it just works. โจ
Modifier: HTML ๐
[0.95] interpolate the parameter with HTML entity encoding. It's giving safe-for-the-web energy. Periodt.
Modifiers: YEAR, DATE(), TIME, and DT() ๐
[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. Bestie, they're not magic, okay?
The actual treatment of a time value depends on the value. Four different situations:
- numeric โ A pure numeric value is considered "seconds since epoch", unless it is smaller than
21000000, in which case it is taken as date without separators. - DateTime object โ [1.00] Use a DateTime object to provide the value. This way, the format does not need to know whether the date is specified as object or as string.
my $now = DateTime->now;
printi "{t YEAR}", t => $now; # works for DateTime, epoch and string
printi "{t.year YEAR}", t => $now; # same effect, DateTime only
printi "{t.year}", t => $now; # will also work, not as nice
- 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.
- date format with time-zone โ By far not all possible date formats are supported, just a few common versions, like
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
The meaning of "05-04-2017" is ambiguous, so not supported. Milliseconds get ignored.
When the provided value has a timezone indication, it will get converted into the local timezone of the observer.
The output of "YEAR" is in format 'YYYY', where "TIME" produces 'HH:mm:ss'. "DT" and "DATE" are configurable.
The DT modifier can produce different formats:
DT(ASC) : %a %b %e %T %Y asctime output (not on Windows)
DT(FT) : %F %T YYYY-MM-DD HH:MM:SS (default)
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
DT(RFC5322) : %a, %d %b %Y %T %z email newest [0.96]
DT(%F-%T) [1.02] any own format
You may suggest additional formats, or add your own modifier. For your own format: be warned that %F and %T are not supported on some Windows versions (but the difference is hidden by Perl >5.38).
[1.02] Also, the DATE modifier can produce different formats:
DATE(-) : %Y-%m-%d
DATE(/) : %Y/%m/%d
DATE(%d-%m-%Y) any own pattern
DATE(%m-%d-%Y) better not use this broken order
Other fields than %Y, %m, and %d are not supported. Other characters are left untouched.
The defaults are:
DATE => { format => '-' },
DT => { format => 'FT' },
Modifier: //word, //"string", //'string' ๐
[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.
"visitors: {count //0}"
"published: {date DT//'not yet'}"
"copyright: {year//2017 YEAR}
Modifiers will usually return "undef" when they are called with an undefined or empty value. By the right order of '//', you may produce different kinds of output:
"price: {price//5 EUR}"
"price: {price EUR//unknown}"
Modifier: '=' (show name) ๐ท๏ธ
[0.96] As (always trailing) modifier, this will show the interpolated name before the value. It might simplify debugging statements. Lowkey a game changer for figuring out what's what.
"visitors: {count=}", count => 1; # visitors: count=1
"v: {count %-8,d =}X", count => 10000; # v: count=10,000โฃโฃX
Modifier: EL or EL($width, [$replace]) โ๏ธ
[1.00] When the string is larger than $width columns, then chop it short and add a 'mid-line ellipsis' character: " โฏ ". You may also pick another replacement string. The comma is optional.
Attention:"columns"not"characters": it is aware of wide fonts, like chinese characters (see%Sabove). The default ellipsis is also two columns wide.
"Intro: {text EL(10)}"; # Intro: 12345678โฏ
"Intro: {text EL(10,โฎ)}"; # Intro: 123456789โฎ
"Intro: {text EL(10โฎ)}"; # Intro: 123456789โฎ
"Intro: {text EL(10,XY)}"; # Intro: 12345678XY
"Intro: {text EL(10XY)}"; # Intro: 12345678XY
The defaults for EL are '20' and 'โฏ' (mid-dots). You can change these with setDefaults():
$sp->setDefaults(EL => { width => 10, replace => 'โฎ' });
$sp->printi("Intro: {text EL}"); # Intro: 12345678โฏ
Modifier: CHOP or CHOP($width, [$units]) ๐ช
[1.00] When the string is larger than $width columns (defaults to 20), then chop it short and add "[+42]": the number of character chopped off. The $width is the size of the result string. The comma is optional.
"Intro: {text CHOP(10)}"; # Intro: 12345[+42]
"Intro: {text CHOP(19 chars)}"; # Intro: 1234578[+33 chars]
"Intro: {text CHOP(19, chars)}"; # Intro: 1234578[+33 chars]
The same effect can be reached by setting the defaults
$sp->setDefaults(CHOP => +{width => 19, units => ' chars'});
$sp->printi("Intro: {text CHOP}", text => $t); # Intro: 1234578[+33 chars]
Other defaults are "head" ("<[") and "tail" ("<]>").
$sp->setDefaults(CHOP => +{head => 'ยซ', tail => 'ยป'});
$sp->printi("Intro: {text CHOP}", text => $t); # Intro: 1234578ยซ+12ยป
Modifier: UNKNOWN or UNKNOWN($width) โ
[1.01] When you need to interpolate a value which is unknown and potentially unsafe, then use this. For instance, you produce an internal error message to report that a method is used incorrectly:
sub openFolder
{ my ($self, $folder) = @_;
blessed $folder && $folder->isa('Mail::Box')
or printi "ERROR: expected a Mail::Box, got a {t UNKNOWN}.",
t => $folder;
}
Now, this $folder parameter is clearly wrong. But what is it? Did we pass a wrong object type? Did we pass a string? An ARRAY maybe?
The "UNKNOWN" modifier distinguishes the following:
- undefined values will be shown as the
UNDEFserializer does; - objects will be represented by their type;
- references will show the first part of their
Data::Dumperdump; and - the leading parts of strings will be shown between double quotes.
Care is taken that weird characters are escaped. The shortening uses the "trim" setting: either 'EL' (default) or 'CHOP'.
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 printp() 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 "\w", so we need a blank to separate the parameter from the modifier.
Stacking modifiers ๐ฅ
You can add more than one modifier. The modifiers detect the extent 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 TIME%10s}!", t => $now; # !โฃโฃ12:59:17!
printp "price: %9{โฌ}s\n", $p; # price: โฃโฃโฃ123.45
printp "!%10{TIME}s!", $now; # !โฃโฃ12:59:17!
Output encoding ๐ค
[0.91] This module is also used by Log::Report::Template, which is used to insert (translated) strings with parameters into HTML templates. You can imagine that some of the parameter may need to be encoded to HTML in the template, and other not.
Example with Log::Report::Template
In pure Template Toolkit, you would write
# in your TT-template
<div>Username: [% username | html %]</div>
# in your code
username => $user->name,
With plain String::Print with output encoding enabled, you can do:
# in your TT-template
<div>[% show_username %]</div>
# in your code with encodeFor('HTML')
show_username => printi("Username: {user}", user => $user->name),
# or
show_username => printp("Username: %s", $user->name),
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:
# in your TT-template
<div>[% show_username %]</div>
# in your code with encodeFor('HTML')
show_username => __x("Username: {user}", user => $user->name),
Shorter:
# in your TT-template with encodeFor('HTML')
<div>[% loc("Username: {user}", user => username) %]</div>
# in your code
username => $user->name,
Even shorter:
# in your TT-template with encodeFor('HTML')
<div>[% loc("Username: {user.name}", user => userobj) %]</div>
# in your code
userobj => $user,
Shortest:
# in your TT-template with encodeFor('HTML')
<div>[% loc("Username: {user.name}") %]</div>
# in your code
user => $user,
Okay and that's shorter than the original version, plus translations for free?! We love an efficiency queen โจ More examples live in Log::Report::Template if you wanna go deeper ๐
๐ธ Output encoding exclusion ๐ธ
Sometimes the data you're inserting is already encoded in whatever output syntax you're targeting. Classic scenario: you literally already have HTML sitting there, ready to be dropped in. No re-encoding needed, bestie ๐
The default exclusion rule for HTML output is qr/html$/i, and what that means is: every inserted named parameter whose name ends in html will not get html-entity encoded. Not even a little. She's exempt ๐
This works right out of the box, no config required:
# with encodeFor('HTML')
printp "Me & Co: {name}, {description_html}",
name => 'RenE<eacute>', description_html => $descr;
And that may result in something like:
Me E<amp>amp; Co: RenE<amp>eacute;, <font color="red">new member</font>
ngl, it's better not to have HTML chillin' in your program at all โ leave that to the template, that's literally what templates are for ๐ But in some cases you just don't have a choice, and that's okay, we're not judging ๐
๐ฆ String::Print compared to other modules on CPAN ๐ฆ
Okay so there are a lot of modules on CPAN that extend printf()'s whole deal. Just to name a few:
String::Format(https://metacpan.org/dist/String-Format)String::Errf(https://metacpan.org/dist/String-Errf)String::Formatter(https://metacpan.org/dist/String-Formatter)Text::Sprintf::Named(https://metacpan.org/dist/Text-Sprintf-Named)Acme::StringFormat(https://metacpan.org/dist/Acme-StringFormat)Text::sprintf(https://metacpan.org/dist/Text-sprintfn)Log::Sprintf(https://metacpan.org/dist/Log-Sprintf)String::Sprintf(https://metacpan.org/dist/String-Sprintf)
And they are all, like, slightly different from each other. Every single one. It's giving "we all showed up in the same outfit but nobody's outfit is actually the same" ๐
Here's the tea tho ๐: when the String::Print module was created, none of the modules listed above handled unicode correctly. Not one. And global configuration of serializers and modifiers was also usually not possible โ sometimes it'd be provided per explicit function call, which, ew. Only String::Print cleanly separates the roles of serializers, modifiers, and conversions. She's the only one with her categories straight, periodt ๐
And on top of all that? String::Print is nicely integrated with Log::Report. Besties fr fr ๐ซถ
๐ SEE ALSO ๐
This module is part of String-Print version 1.02, built on December 09, 2025. Website: http://perl.overmeer.net/CPAN/
๐ LICENSE ๐
For contributors see file ChangeLog.
This software is copyright (c) 2016-2025 by Mark Overmeer. Iconic, we stan an author who's been holding it down since 2016 ๐
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Go wild, bestie โจ
And that's the whole page, babes! ๐ This rendition came to you from perl v5.40.1, dated 2025-12-09, and it's String::Print(3pm) โ thanks for reading all four parts, you're genuinely the main character for that ๐ Go format some strings, you absolute legend ๐โญ
๐ฆ where this page comes from
- ubuntu resolute: libstring-print-perl 1.02-1 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libstring-print-perl 1.02-1 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms