String-Print-1.02/0000755000175000001440000000000015116015375014516 5ustar00markovusers00000000000000String-Print-1.02/README.md0000644000175000001440000000416215114025556016000 0ustar00markovusers00000000000000# distribution String-Print This module inserts values into (format) strings. It provides printf() and sprintf() alternatives via both an object oriented and a functional interface. * My extended documentation: * Development via GitHub: * Sponsor me: * Download from CPAN: * Indexed from CPAN: ## Installing On github, you can find the processed version for each release. But the better source is CPAN; to get it installed simply run: ```sh cpan -i String::Print ``` ## Development → Release Important to know, is that I use an extension on POD to write the manuals. The "raw" unprocessed version is visible on GitHub. It will run without problems, but does not contain manual-pages. Releases to CPAN are different: "raw" documentation gets removed from the code and translated into real POD and clean HTML. This reformatting is implemented with the OODoc distribution (A name I chose before OpenOffice existed, sorry for the confusion) Clone from github for the "raw" version. For instance, when you want to contribute a new feature. ## Contributing When you want to contribute to this module, you do not need to provide a perfect patch... actually: it is nearly impossible to create a patch which I will merge without modification. Usually, I need to adapt the style of code and documentation to my own strict rules. When you submit an extension, please contribute a set with 1. code 2. code documentation 3. regression tests in t/ **Please note:** When you contribute in any way, you agree to transfer the copyrights to Mark Overmeer (you will get the honors in the code and/or ChangeLog). You also automatically agree that your contribution is released under the same license as this project: licensed as perl itself. ## Copyright and License This project is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See String-Print-1.02/t/0000755000175000001440000000000015116015375014761 5ustar00markovusers00000000000000String-Print-1.02/t/14missing.t0000644000175000001440000000101215057535073016764 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test reporting of missing parameters use warnings; use strict; use Test::More; use String::Print; my $f = String::Print->new; isa_ok($f, 'String::Print'); is $f->sprinti('testA {a}', a => undef), 'testA undef', 'undef is not missing'; my $warning; $SIG{__WARN__} = sub { $warning = join '/', @_ }; my $file = __FILE__; my $line = __LINE__ + 1; is $f->sprinti('testB {b}'), 'testB undef', 'missing'; is $warning, "Missing key 'b' in format 'testB {b}', file $file line $line\n"; done_testing; String-Print-1.02/t/53m_default.t0000644000175000001440000000255515115534256017270 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test the 'undef default' modifier use warnings; use strict; use utf8; use Test::More; use String::Print; my $f = String::Print->new; isa_ok($f, 'String::Print'); ### these are all examples from the manual page is $f->sprinti("visitors: {count //0}", count => 1), "visitors: 1", 'count'; is $f->sprinti("visitors: {count //0}", count => undef), "visitors: 0"; is $f->sprinti("visitors: {count//0}", count => undef), "visitors: 0"; is $f->sprinti("published: {date DT//'not yet'}", date => undef), "published: not yet", 'date'; is $f->sprinti('published: {date DT//"not yet"}', date => undef), "published: not yet"; is $f->sprinti("published: {date DT//'not yet'}", date => "2017-06-25 12:35:00"), "published: 2017-06-25 12:35:00"; is $f->sprinti("copyright: {year//2017 YEAR}", year => " 2018 "), 'copyright: 2018', 'year'; is $f->sprinti("copyright: {year//2017 YEAR}", year => undef), 'copyright: 2017'; $f->addModifiers(qw/EUR\b/ => sub { my ($sp, $format, $value, $args) = @_; defined $value ? "$value€" : undef; }); is $f->sprinti("price: {price//5 EUR}", price => 3), 'price: 3€', 'price'; is $f->sprinti("price: {price//5 EUR}", price => undef), 'price: 5€'; is $f->sprinti("price: {price EUR//unknown}", price => 3), 'price: 3€'; is $f->sprinti("price: {price EUR//unknown}", price => undef), 'price: unknown'; done_testing; String-Print-1.02/t/58_unknown.t0000644000175000001440000000244115114326067017163 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test the UNKNOWN modifier use warnings; use strict; use utf8; use Test::More; use String::Print; my $f = String::Print->new; isa_ok($f, 'String::Print'); is $f->sprinti("A {text UNKNOWN}", text => 'this text is short'), 'A "this text is short"', 'short text'; is $f->sprinti("B {text UNKNOWN}", text => "newline\n and tab\t."), 'B "newline\n and tab\t."', 'newline and tab'; is $f->sprinti("C {text UNKNOWN(10)}", text => 'this text is short'), 'C "this tex⋯ "', 'shortened text'; is $f->sprinti("D {array UNKNOWN}", array => [1, 2]), 'D [1,2]', 'short array'; is $f->sprinti("E {array UNKNOWN(10)}", array => [1..10]), 'E [1,2,3,4,⋯ ]', 'shortened array'; is $f->sprinti("F {hash UNKNOWN}", hash => { a => 1 }), 'F {a => 1}', 'short hash'; is $f->sprinti("G {hash UNKNOWN(10)}", hash => {a => 1, b => 2, c => 3}), 'G {a => 1,b⋯ }', 'shortened hash'; is $f->sprinti("H {class UNKNOWN}", class => $f), 'H String::Print', 'class'; is $f->sprinti("I {class UNKNOWN(5)}", class => $f), 'I String::Print', 'class not trimmed'; $f->setDefaults(UNKNOWN => { trim => 'CHOP', width => 15 }); is $f->sprinti("J {text UNKNOWN}", text => 'this is a much longer line'), 'J "this is a [+16]"', 'chop shortened text'; #XXX this needs testing for wide and zero-width strings done_testing; String-Print-1.02/t/52m_dates.t0000644000175000001440000000651215116015372016732 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test the date modifiers use warnings; use strict; use utf8; use Test::More; use String::Print; my $f = String::Print->new; isa_ok($f, 'String::Print'); #XXX Date routines easily break on local system differences, so run most #XXX tests only on my private development system. For instance, the TZ might #XXX be different and not settable in some environments. my $devel = $ENV{MARKOV_DEVEL} || 0; my $now = 1498224823; is $f->sprinti("{t YEAR}", t => '2017'), '2017', 'year'; is $f->sprinti("{t YEAR}", t => '2017-06-23'), '2017', 'year'; is $f->sprinti("{t YEAR}", t => $now), '2017', 'year'; is $f->sprinti("{t DATE}", t => '2017-06-23'), '2017-06-23', 'date'; is $f->sprinti("{t DATE}", t => '2017-06-23 15:50'), '2017-06-23', 'date'; is $f->sprinti("{t DATE}", t => '2017/06/23'), '2017-06-23', 'date'; is $f->sprinti("{t DATE}", t => '2017.06.23'), '2017-06-23', 'date'; is $f->sprinti("{t DATE}", t => '20170623'), '2017-06-23', 'date'; is $f->sprinti("{t DATE}", t => '2017-6-23'), '2017-06-23', 'date'; is $f->sprinti("{t DATE(-)}", t => '2017-06-23'), '2017-06-23', 'date format -'; is $f->sprinti("{t DATE(/)}", t => '2017/06/23'), '2017/06/23', 'date format /'; is $f->sprinti("{t DATE(%d-%m-%Y)}", t => '2017-06-23'), '23-06-2017', 'date format flex'; if($devel) { # timezone may influence date is $f->sprinti("{t DATE}", t => $now), '2017-06-23', 'date'; } is $f->sprinti("{t TIME}", t => '13:33:43') , '13:33:43', 'time'; is $f->sprinti("{t TIME}", t => ' 13:33') , '13:33:00', 'time'; is $f->sprinti("{t TIME}", t => '2017-06-23 13:33:43'), '13:33:43', 'time'; is $f->sprinti("{t TIME}", t => '2017-06-23 13:33'), '13:33:00', 'time'; if($devel) { # timezone does always influence time is $f->sprinti("{t TIME}", t => $now), '15:33:43', 'time'; } ### DT if($devel) { # str2time ignores timezone if none given is $f->sprinti("{t DT}", t => '2017-06-23 13:33:43'), '2017-06-23 13:33:43', 'dt'; is $f->sprinti("{t DT}", t => $now), '2017-06-23 15:33:43', 'dt default'; is $f->sprinti("{t DT(FT)}", t => $now), '2017-06-23 15:33:43', 'dt FT'; is $f->sprinti("{t DT}", t => '2017-06-23 13:33:43+2'), '2017-06-23 13:33:43', 'dt'; is $f->sprinti("{t DT}", t => '2017-06-23 13:33:43-25:15'), '2017-06-24 16:48:43', 'dt'; is $f->sprinti("{t DT(ISO)}", t => '2017-06-23 13:33:43+2'), '2017-06-23T13:33:43+0200', 'dt iso'; is $f->sprinti("{t DT(RFC2822)}", t => '2017-06-23 13:33:43+2'), 'Fri, 23 Jun 2017 13:33:43 +0200', 'dt rfc2822'; is $f->sprinti("{t DT(RFC822)}", t => '2017-06-23 13:33:43+2'), 'Fri, 23 Jun 17 13:33:43 +0200', 'dt rfc822'; # %e in ASC is not supported under Windows is $f->sprinti("{t DT(ASC)}", t => '2017-06-23 13:33:43+2'), 'Fri Jun 23 13:33:43 2017', 'dt asc'; $f->setDefaults(DT => { format => 'ISO' }); is $f->sprinti("{t DT}", t => $now), '2017-06-23T15:33:43+0200', 'dt setDefault'; is $f->sprinti("{t DT(%H)}", t => '2017-06-23 13:33:43+2'), '13', 'dt format flex'; } ### DateTime object if($devel) { require DateTime; my $dt = DateTime->from_epoch(epoch => $now); is $f->sprinti("{t YEAR}", t => $dt), '2017', 'DateTime year'; is $f->sprinti("{t DATE}", t => $dt), '2017-06-23', 'DateTime date'; is $f->sprinti("{t TIME}", t => $dt), '13:33:43', 'DateTime time'; is $f->sprinti("{t DT(FT)}", t => $now), '2017-06-23 15:33:43', 'DateTime dt'; } done_testing; String-Print-1.02/t/30examp_oo.t0000644000175000001440000000233515057535073017131 0ustar00markovusers00000000000000#!/usr/bin/env perl # Demonstrate the OO examples use warnings; use strict; use Test::More tests => 7; use String::Print 'oo'; use POSIX qw/strftime/; # ### currency conversion example # my $f = String::Print->new ( modifiers => [ EUR => sub { sprintf "%5.2f e", $_[2] } ] , serializers => [ UNDEF => sub {'-'} ] ); isa_ok($f, 'String::Print'); is($f->sprinti("price: {p EUR}#", p => 3.1415), 'price: 3.14 e#'); is($f->sprinti("count: {c}#", c => undef), 'count: -#'); # ### date-time conversion # $f->addModifiers( qr/T|DT|D/ => sub { my ($formatter, $modif, $value, $args) = @_; # Windows does not support full POSIX, no %T nor %F my $time_format = $modif eq 'T' ? '%H:%M:%S' : $modif eq 'D' ? '%Y-%m-%d' : $modif eq 'DT' ? '%Y-%m-%dT%H:%M:%SZ' : 'ERROR'; strftime $time_format, gmtime($value); } ); my $now = 1365850757; is($f->sprinti("time: {t T }", t => $now), 'time: 10:59:17', 'time'); is($f->sprinti("date: {t D }", t => $now), 'date: 2013-04-13', 'date'); is($f->sprinti("both: {t DT}", t => $now), 'both: 2013-04-13T10:59:17Z', 'dateTime'); is($f->sprinti("#{t T%10s}#", t => $now), '# 10:59:17#', 'stacked'); String-Print-1.02/t/54m_html.t0000644000175000001440000000047115057535073016607 0ustar00markovusers00000000000000#!/usr/bin/env perl # Check modifier HTML use warnings; use strict; use utf8; use Test::More; use String::Print; my $g = String::Print->new; isa_ok($g, 'String::Print'); is $g->sprinti("Hello & greetz {name HTML}", name => "André"), 'Hello & greetz André', 'html modifier'; done_testing; String-Print-1.02/t/00use.t0000644000175000001440000000122615057535073016111 0ustar00markovusers00000000000000#!/usr/bin/env perl use warnings; use strict; use Test::More tests => 1; # The versions of the following packages are reported to help understanding # the environment in which the tests are run. This is certainly not a # full list of all installed modules. my @show_versions = qw/ Test::More Unicode::GCString HTML::Entities /; warn "Perl $]\n"; foreach my $package (sort @show_versions) { eval "require $package"; my $report = !$@ ? "version ". ($package->VERSION || 'unknown') : $@ =~ m/^Can't locate/ ? "not installed" : "reports error"; warn "$package $report\n"; } use_ok('String::Print'); String-Print-1.02/t/13subnames.t0000644000175000001440000000145715057535073017144 0ustar00markovusers00000000000000#!/usr/bin/env perl # Use of sub-naming schemes. use warnings; use strict; use Test::More tests => 8; use String::Print; my $f = String::Print->new; isa_ok($f, 'String::Print'); is $f->sprinti('{a}', a => 'simple'), 'simple'; is $f->sprinti('{a.b}', a => {b => 'nested'}), 'nested'; is $f->sprinti('{a.b%-10s}', a => {b => 'format'}), 'format '; is $f->sprinti('{a.b.c}', a => {b => {c => 'deeper'}}), 'deeper'; sub b() { +{ c => 'via code' } } is $f->sprinti('{a.b.c}', a => {b => \&b}), 'via code', 'code ref'; { package USER; sub new() { bless { name => $_[1] }, $_[0] } sub name() { $_[0]->{name} } sub count() { 42 } } my $user = USER->new('Mark'); is $f->sprinti('{user.name}', user => $user), 'Mark', 'object method'; is $f->sprinti('{user.count}', user => 'USER'), 42, 'class method'; String-Print-1.02/t/55m_name.t0000644000175000001440000000077215114025556016562 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test the 'name' modifier use warnings; use strict; use utf8; use Test::More; use String::Print; my $f = String::Print->new; isa_ok($f, 'String::Print'); ### these are all examples from the manual page is $f->sprinti("visitors: {count=}", count => 1), "visitors: count=1", 'simple'; is $f->sprinti("visitors: {count%05d =}", count => 2), "visitors: count=00002", 'stack'; is $f->sprinti("visitors: {count %-8,d =}X", count => 10_000), "visitors: count=10,000 X"; done_testing; String-Print-1.02/t/50m_format.t0000644000175000001440000000460715115534256017131 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test sprintf formatting use warnings; use strict; use utf8; use Test::More; use String::Print; my $pi = 3.14157; my $f = String::Print->new; isa_ok($f, 'String::Print'); my $x1 = $f->sprinti("a={a%d} b={b %.2f}", a => 007, b => $pi); $x1 =~ s/,/./g; # locale may output floats with comma is $x1, "a=7 b=3.14"; is $f->sprinti("x={v%_d}", v => 1e9), 'x=1_000_000_000'; is $f->sprinti("x={v%,d}", v => 1e9), 'x=1,000,000,000'; is $f->sprinti("x={v%.d}", v => 1e9), 'x=1.000.000.000'; is $f->sprinti("x={v%.d}", v => 1e8), 'x=100.000.000'; is $f->sprinti("x={v%,d}", v => 1e8), 'x=100,000,000'; is $f->sprinti("x={v%.d}", v => 1e7), 'x=10.000.000'; is $f->sprinti("x={v%.d}", v => 1e6), 'x=1.000.000'; is $f->sprinti("x={v%,d}", v => 1e6), 'x=1,000,000'; is $f->sprinti("x={v%.d}", v => 1e5), 'x=100.000'; is $f->sprinti("x={v%.d}", v => 1e4), 'x=10.000'; is $f->sprinti("x={v%.d}", v => 1e3), 'x=1.000'; is $f->sprinti("x={v%.d}", v => 100), 'x=100'; is $f->sprinti("x={v%.d}", v => 10), 'x=10'; is $f->sprinti("x={v%.d}", v => 1), 'x=1'; is $f->sprinti("x={v%.d}", v => 0), 'x=0'; is $f->sprinti("x={v%_d}", v => -1e4), 'x=-10_000'; is $f->sprinti("x={v%+_d}", v => -1e4), 'x=-10_000'; is $f->sprinti("x={v%+_d}", v => 1e4), 'x=+10_000'; is $f->sprinti("x={v% _d}", v => 1e4), 'x= 10_000'; is $f->sprinti("x={v%-10.d}", v => 1e4), 'x=10.000 '; is $f->sprinti("x={v%10.d}", v => 1e4), 'x= 10.000'; is $f->sprinti("x={v%-10.d}", v => -1e4), 'x=-10.000 '; is $f->sprinti("x={v%10.d}", v => -1e4), 'x= -10.000'; # multi-byte characters my $short = "€éö"; is $f->sprinti("c={z%s}x", z => $short), "c=${short}x"; is $f->sprinti("c2={z %s}x", z => $short), "c2=${short}x"; is $f->sprinti("c3={ z%s}x", z => $short), "c3=${short}x"; is $f->sprinti("c4={ z %s}x", z => $short), "c4=${short}x"; is $f->sprinti("d={z%5s}x", z => $short), "d= ${short}x"; is $f->sprinti("e={z%-5s}x", z => $short), "e=${short} x"; is $f->sprinti("f={z%5s}x", z => "${short}yzzz"), "f=${short}yzzzx"; is $f->sprinti("g={z%.5s}x", z => "${short}yzz"), "g=${short}yzx", 'too large'; is $f->sprinti("h={z%5.3s}x",z => "${short}yz"), "h= ${short}x"; is $f->sprinti("i={z%-5.3s}x",z=> "${short}yz"), "i=${short} x"; $f->setDefaults(FORMAT => { thousands => ',' }); is $f->sprinti("x={v%d}", v => 1e9), 'x=1,000,000,000', 'default thousands'; #XXX Now re-run the tests with wide display chars. done_testing; String-Print-1.02/t/10serial.t0000644000175000001440000000307315057535073016577 0ustar00markovusers00000000000000#!/usr/bin/env perl # Serialize variables when sprinti'd use warnings; use strict; use Test::More tests => 16; use String::Print; my $f = String::Print->new; isa_ok($f, 'String::Print'); is($f->sprinti("#{v}#", v => undef), '#undef#', 'UNDEF'); is($f->sprinti("#{v}#", v => ''), '##' , 'empty string'); is($f->sprinti("#{v}#", v => 42), '#42#' , 'string'); is($f->sprinti("#{v}#", v => [12,13]),'#12, 13#', 'ARRAY'); is($f->sprinti("#{v}#", v => [14,15], _join => ' '),'#14 15#'); { local $" = ':'; is($f->sprinti("#{v}#", v => [16,17], _join => $"), '#16:17#'); } is($f->sprinti("#{v}#", v => {a => 3, b => 5}) ,'#a => 3, b => 5#', 'HASH'); is($f->sprinti("#{v}#", v => sub {18}),'#18#', 'CODE'); is($f->sprinti("#{v}#", v => sub {sub {19}}),'#19#', 'CODE CODE'); is($f->sprinti("#{v}#", v => \50),'#50#', 'SCALAR'); is($f->sprinti("#{v}#", v => \undef),'#undef#', 'SCALAR undef'); my $g = String::Print->new ( serializers => [ UNDEF => sub {'(undef)'} , ARRAY => sub {join '|', reverse @{$_[1]} } , MyObj => \&name_in_reverse ] ); isa_ok($g, 'String::Print'); is($g->sprinti("#{v}#", v => undef), '#(undef)#'); is($g->sprinti("#{v}#", v => [8..13]),'#13|12|11|10|9|8#'); # ### Object interpolation # used as example in man-page # { package MyObj; sub name() {shift->{name}} } my $obj = bless {name => 'my-name'}, 'MyObj'; is($g->sprinti("#{v}#", v => $obj),'#eman-ym#'); sub name_in_reverse($$$) { my ($formatter, $object, $args) = @_; # the $args are all parameters to be filled-in scalar reverse $object->name; } String-Print-1.02/t/20prewrite.t0000644000175000001440000000353715057543072017165 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test printp rewrite use warnings; use strict; use Test::More; use String::Print; sub rewrite($$$) { my ($pargs, $i, $iargs) = @_; my $p = $pargs->[0]; my ($goti, $gota) = String::Print::_printp_rewrite($pargs); #use Data::Dumper; #warn Dumper $goti, $gota; ok(defined $goti, "rewrite $p"); is($goti, $i, "into $i"); cmp_ok(scalar @$iargs, '==', scalar @$gota, 'check returned arg length'); foreach(my $i=0; $i<@$iargs; $i++) { cmp_ok($iargs->[$i], 'eq', $gota->[$i], "param $i = $iargs->[$i]"); } } rewrite(['aap'], 'aap', []); rewrite(['%d', '41'], '{_1%d}', [_1 => 41] ); rewrite(['a%db', '42'], 'a{_1%d}b', [_1 => 42] ); rewrite(['a%sb', '43'], 'a{_1}b', [_1 => 43] ); rewrite(['a%5sb', '44'], 'a{_1%5s}b', [_1 => 44] ); rewrite(['a%.3sb', '45'], 'a{_1%.3s}b', [_1 => 45] ); rewrite(['a%2.3sb', '46'], 'a{_1%2.3s}b', [_1 => 46] ); rewrite(['a%2.3{T}sb', '47'], 'a{_1 T%2.3s}b', [_1 => 47] ); rewrite(['a%-2sb', '48'], 'a{_1%-2s}b', [_1 => 48] ); rewrite(['a%-.3sb', '49'], 'a{_1%-.3s}b', [_1 => 49] ); rewrite(['a%sb c%sd', '50', 51], 'a{_1}b c{_2}d', [_1 => 50, _2 => 51] ); rewrite(['a%*db c%*sd', 3, 4, 5, 6, x => 5], 'a{_2%3d}b c{_4%5s}d', [_2 => 4, _4 => 6, x => 5] ); rewrite(['a%2.*db c%.*sd', 3, 4, 5, 6, y => 6], 'a{_2%2.3d}b c{_4%.5s}d', [_2 => 4, _4 => 6, y => 6] ); rewrite(['a%*.*sb', 11, 12, 13, r => 42], 'a{_3%11.12s}b', [_3 => 13, r => 42]); rewrite(['a%1$sb c%2$dd', 14, 15, z => 13], 'a{_1}b c{_2%d}d', [_1 => 14, _2 => 15, z => 13] ); rewrite(['a%2$-1.6sb c%1$dd', 16, 17, z => 18], 'a{_2%-1.6s}b c{_1%d}d', [_2 => 17, _1 => 16, z => 18] ); rewrite(['a%2$*.*sb c%1$dd', 1, 2, 4, 5, r => 19], 'a{_4%2.4s}b c{_1%d}d', [_4 => 5, _1 => 1, r => 19 ] ); rewrite([ '%s', 21, _join => '#' ], '{_1}', [ _1 => 21, _join => '#'] ); done_testing; String-Print-1.02/t/51m_bytes.t0000644000175000001440000000176615115534256016773 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test BYTES modifier use warnings; use strict; use utf8; use Test::More; use String::Print; my $f = String::Print->new; isa_ok($f, 'String::Print'); sub fill($$) { my ($expected, $count) = @_; my $show = $f->sprinti("{a BYTES}", a => $count); $show =~ s/\,/./g; # depends on effective locale is $show, $expected, $expected; } use constant KB => 1024; fill ' 0 B', 0; ### no fraction fill ' 1 B', 1; fill ' 10 B', 10; fill '100 B', 100; fill '999 B', 999; ### numeric resolution fill '1.0kB', 1000; fill '1.0kB', 1 * KB; fill '1.5kB', 1.5 * KB; fill '1.7kB', 1.66 * KB; # 0.05 is 1/20 of 1024, not 1000 fill '9.9kB', 9.94 * KB; fill ' 10kB', 9.95 * KB; fill '999kB', 999 * KB; ### large numbers fill '1.5MB', 1.5 * KB * KB; fill ' 11MB', 10.6 * KB * KB; fill '1.5GB', 1.5 * KB * KB * KB; fill ' 11GB', 10.6 * KB * KB * KB; fill '1.5TB', 1.5 * KB * KB * KB * KB; fill ' 11TB', 10.6 * KB * KB * KB * KB; ### out of range fill '84703ZB', 10e25; done_testing; String-Print-1.02/t/12encode.t0000644000175000001440000000137615057535073016563 0ustar00markovusers00000000000000#!/usr/bin/env perl # Output encoding (to HTML) use warnings; use strict; use utf8; use Test::More tests => 7; use String::Print; my $f = String::Print->new(encode_for => 'HTML'); isa_ok($f, 'String::Print'); # encode HTML, all is $f->sprinti('Me & You'), 'Me & You'; is $f->sprinti('< {a} >', a => 'Me & You'), '< Me & You >'; # exclude HTML encoding for names =~ /html$/i is $f->sprinti('<{a_html}>', a_html => 'Me & You'), '<Me & You>'; is $f->sprinti('<{aHTML}>', aHTML => 'Me & You'), '<Me & You>'; # disable encoding $f->encodeFor(undef); is $f->sprinti('< {a} >', a => 'Me & You'), '< Me & You >'; # enable encoding $f->encodeFor('HTML'); is $f->sprinti('< {a} >', a => 'Me & You'), '< Me & You >'; String-Print-1.02/t/57_chop.t0000644000175000001440000000307315114326067016416 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test the chop modifier use warnings; use strict; use utf8; use Test::More; use String::Print; my $f = String::Print->new; isa_ok($f, 'String::Print'); my $text1 = "123456789012345678901234567890"; cmp_ok length($text1), '==', 30, 'check text length'; is $f->sprinti("Intro: {text}", text => $text1), "Intro: $text1", 'no modifier'; is $f->sprinti("Intro: {text CHOP(50)}", text => $text1), "Intro: $text1", 'fits in field easily'; ### these are all examples from the manual page is $f->sprinti("Intro: {text CHOP(25)}", text => $text1), "Intro: 123456789012345678901[+9]", 'chop short'; is $f->sprinti("Intro: {text CHOP(25 chars)}", text => $text1), "Intro: 12345678901234[+16 chars]", 'chop short with extra'; is $f->sprinti("Intro: {text CHOP(10)}", text => $text1), "Intro: 12345[+25]", 'chop short'; is $f->sprinti("Intro: {text CHOP(12 chars)}", text => $text1), "Intro: 1[+29 chars]", 'chop short with extra'; is $f->sprinti("Intro: {text CHOP(3)}", text => $text1), "Intro: [30]", 'chop too short'; is $f->sprinti("Intro: {text CHOP(5 chars)}", text => $text1), "Intro: [30 chars]", 'chop too short with extra'; $f->setDefaults(CHOP => +{width => 19, units => ' chars'}); is $f->sprinti("Intro: {text CHOP}", text => $text1), 'Intro: 12345678[+22 chars]', 'chop with changed defaults'; $f->setDefaults(CHOP => +{head => '«', tail => '»', width => 20}); is $f->sprinti("Intro: {text CHOP}", text => $text1), 'Intro: 123456789012345«+15»', 'chop with other head/tail'; #XXX this needs testing for wide and zero-width strings done_testing; String-Print-1.02/t/40utf8.t0000644000175000001440000000106715057535073016212 0ustar00markovusers00000000000000#!/usr/bin/env perl # difficult utf8 situations use warnings; use strict; use utf8; use Test::More tests => 7; use Encode qw/is_utf8/; use String::Print 'sprintp'; my $latin1 = chr 230; # æ ok(!is_utf8 $latin1); my $format = "a${latin1}b%sc"; my $out1 = sprintp $format, 'z'; ok(is_utf8($out1), 'formatted with normal param'); is($out1, 'aæbzc'); my $out2 = sprintp $format, $latin1; ok(is_utf8($out2), 'formatted with latin1'); is($out2, 'aæbæc'); my $out3 = sprintp $format, 'Ø'; ok(is_utf8($out3), 'formatted with utf8'); is($out3, 'aæbØc'); String-Print-1.02/t/11modif.t0000644000175000001440000000127315061005575016411 0ustar00markovusers00000000000000#!/usr/bin/env perl # Check modifiers use warnings; use strict; use utf8; use Test::More; use String::Print; my $pi = 3.1415; sub money($$$$) { my ($formatter, $modif, $value, $args) = @_; # warn "($formatter, $modif, $value, $args)\n"; $modif eq '€' ? sprintf("%.2f EUR", $value) : $modif eq '₤' ? sprintf("%.2f PND", $value/1.23) : 'ERROR'; } my $g = String::Print->new ( modifiers => [ qr/[€₤]/ => \&money ] ); isa_ok($g, 'String::Print'); is $g->sprinti("a={p€}", p => $pi), "a=3.14 EUR"; is $g->sprinti("b={p₤}", p => $pi), "b=2.55 PND"; is $g->sprinti("a={p€%10s}", p => $pi), "a= 3.14 EUR", 'stacking modifiers'; done_testing; String-Print-1.02/t/56_ellipsis.t0000644000175000001440000000263515114326067017313 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test the ellipsis modifier use warnings; use strict; use utf8; use Test::More; use String::Print; my $f = String::Print->new; isa_ok($f, 'String::Print'); my $text1 = "123456789012345678901234567890"; is $f->sprinti("Intro: {text}", text => $text1), "Intro: $text1", 'no modifier'; is $f->sprinti("Intro: {text EL(50)}", text => $text1), "Intro: $text1", 'fits in field easily'; ### these are all examples from the manual page is $f->sprinti("Intro: {text EL(10)}", text => $text1), "Intro: 12345678⋯ ", 'default ellipsis'; is $f->sprinti("Intro: {text EL(10,)}", text => $text1), "Intro: 12345678⋯ ", 'default ellipsis, empty replace'; is $f->sprinti("Intro: {text EL(1,)}", text => $text1), "Intro: ⋯ ", 'replace too large'; is $f->sprinti("Intro: {text EL(10,⋮)}", text => $text1), "Intro: 123456789⋮", 'vertical ellipsis'; is $f->sprinti("Intro: {text EL(10⋮)}", text => $text1), "Intro: 123456789⋮", 'vertical ellipsis without comma'; is $f->sprinti("Intro: {text EL(10,XY)}", text => $text1), "Intro: 12345678XY", 'longer replacement'; is $f->sprinti("Intro: {text EL(10XY)}", text => $text1), "Intro: 12345678XY", 'longer replacement without comma'; # Defaults $f->setDefaults(EL => { width => 20 }); is $f->sprinti("Intro: {text EL}", text => $text1), "Intro: 123456789012345678⋯ ", 'defaults'; #XXX this needs testing for wide and zero-width strings done_testing; String-Print-1.02/t/31examp_fun.t0000644000175000001440000000113315057535073017300 0ustar00markovusers00000000000000#!/usr/bin/env perl # Demonstrate the functional examples use warnings; use strict; use Test::More tests => 4; use String::Print 'sprinti', 'sprintp' , modifiers => [ EUR => sub { sprintf "%5.2f e", $_[2] } ] , serializers => [ UNDEF => sub {'-'} ]; is(sprinti("price: {p EUR}#", p => 3.1415), 'price: 3.14 e#'); is(sprinti("count: {c}#", c => undef), 'count: -#'); my @dumpfiles = qw/f1 f2/; is(sprintp("dumpfiles: %s\n", \@dumpfiles, _join => ', ') , "dumpfiles: f1, f2\n"); is(sprinti("dumpfiles: {filenames}\n",filenames => \@dumpfiles, _join => ', ') , "dumpfiles: f1, f2\n"); String-Print-1.02/xt/0000755000175000001440000000000015116015375015151 5ustar00markovusers00000000000000String-Print-1.02/xt/99pod.t0000644000175000001440000000041615057535073016311 0ustar00markovusers00000000000000#!/usr/bin/env perl use warnings; use strict; use Test::More; BEGIN { eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; plan skip_all => "devel home uses OODoc" if $ENV{MARKOV_DEVEL}; } all_pod_files_ok(); String-Print-1.02/MANIFEST0000644000175000001440000000101315116015375015642 0ustar00markovusers00000000000000ChangeLog MANIFEST Makefile.PL README.md lib/String/Print.pm lib/String/Print.pod t/00use.t t/10serial.t t/11modif.t t/12encode.t t/13subnames.t t/14missing.t t/20prewrite.t t/30examp_oo.t t/31examp_fun.t t/40utf8.t t/50m_format.t t/51m_bytes.t t/52m_dates.t t/53m_default.t t/54m_html.t t/55m_name.t t/56_ellipsis.t t/57_chop.t t/58_unknown.t xt/99pod.t META.yml Module YAML meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) String-Print-1.02/lib/0000755000175000001440000000000015116015375015264 5ustar00markovusers00000000000000String-Print-1.02/lib/String/0000755000175000001440000000000015116015375016532 5ustar00markovusers00000000000000String-Print-1.02/lib/String/Print.pm0000644000175000001440000004545415116015372020175 0ustar00markovusers00000000000000# This code is part of Perl distribution String-Print version 1.02. # The POD got stripped from this file by OODoc version 3.05. # For contributors see file ChangeLog. # This software is copyright (c) 2016-2025 by Mark Overmeer. # This is free software; you can redistribute it and/or modify it under # the same terms as the Perl 5 programming language system itself. # SPDX-License-Identifier: Artistic-1.0-Perl OR GPL-1.0-or-later package String::Print;{ our $VERSION = '1.02'; } use warnings; use strict; use utf8; #use Log::Report::Optional 'log-report'; use Unicode::GCString (); use Data::Dumper (); use Date::Parse qw/str2time/; use Encode qw/is_utf8 decode/; use HTML::Entities qw/encode_entities/; use POSIX qw/strftime/; use Scalar::Util qw/blessed reftype/; my @default_modifiers = ( qr/\% ?\S+/ => \&_modif_format, qr/BYTES\b/ => \&_modif_bytes, qr/HTML\b/ => \&_modif_html, qr/YEAR\b/ => \&_modif_year, qr/TIME\b/ => \&_modif_time, qr/\=/ => \&_modif_name, qr/DATE\([^)]*\)|DATE\b/ => \&_modif_date, qr/DT\([^)]*\)|DT\b/ => \&_modif_dt, qr!UNKNOWN\([0-9]+\)|UNKNOWN\b! => \&_modif_unknown, qr!CHOP\([0-9]+(?:\,?[^)]*)\)|CHOP\b! => \&_modif_chop, qr!EL\([0-9]+(?:\,?[^)]*)\)|EL\b! => \&_modif_ellipsis, qr!//(?:\"[^"]*\"|\'[^']*\'|\w+)! => \&_modif_undef, ); # Be warned: %F and %T (from C99) are not always supported on Windows my %dt_format = ( ASC => '%a %b %e %H:%M:%S %Y', ISO => '%Y-%m-%dT%H:%M:%S%z', RFC822 => '%a, %d %b %y %H:%M:%S %z', RFC2822 => '%a, %d %b %Y %H:%M:%S %z', RFC5322 => '%a, %d %b %Y %H:%M:%S %z', FT => '%Y-%m-%d %H:%M:%S', ); my %date_format = ( '-' => '%Y-%m-%d', '/' => '%Y/%m/%d', ); my %defaults = ( CHOP => +{ width => 30, head => '[', units => '', tail => ']' }, DATE => +{ format => $date_format{'-'}, }, DT => +{ format => $dt_format{FT}, }, EL => +{ width => 30, replace => '⋯ '}, FORMAT => +{ thousands => '' }, UNKNOWN => +{ width => 30, trim => 'EL' }, ); my %default_serializers = ( UNDEF => sub { 'undef' }, '' => sub { $_[1] }, SCALAR => sub { ${$_[1]} // shift->{SP_seri}{UNDEF}->(@_) }, ARRAY => sub { my $v = $_[1]; my $join = $_[2]{_join} // ', '; join $join, map +($_ // 'undef'), @$v }, HASH => sub { my $v = $_[1]; join ', ', map "$_ => ".($v->{$_} // 'undef'), sort keys %$v }, # CODE value has different purpose ); my %predefined_encodings = ( HTML => { exclude => [ qr/html$/i ], encode => sub { encode_entities $_[0] }, }, ); sub new(@) { my $class = shift; (bless {}, $class)->init( +{@_} ) } sub init($) { my ($self, $args) = @_; my $modif = $self->{SP_modif} = [ @default_modifiers ]; if(my $m = $args->{modifiers}) { unshift @$modif, @$m; } my $s = $args->{serializers} || {}; my $seri = $self->{SP_seri} = +{ %default_serializers, (ref $s eq 'ARRAY' ? @$s : %$s) }; $self->{SP_defs} = +{ %defaults }; # the HASHes get copied when changed. $self->setDefaults($args->{defaults}) if $args->{defaults}; $self->encodeFor($args->{encode_for}); $self->{SP_missing} = $args->{missing_key} || \&_reportMissingKey; $self; } sub import(@) { my $class = shift; my ($oo, %func); while(@_) { last if $_[0] !~ m/^s?print[ip]$/; $func{shift()} = 1; } if(@_ && $_[0] eq 'oo') { # import only object oriented interface shift @_; @_ and die "no options allowed at import with oo interface"; return; } my $all = !keys %func; my $f = $class->new(@_); # OO encapsulated my ($pkg) = caller; no strict 'refs'; *{"$pkg\::printi"} = sub { $f->printi(@_) } if $all || $func{printi}; *{"$pkg\::sprinti"} = sub { $f->sprinti(@_) } if $all || $func{sprinti}; *{"$pkg\::printp"} = sub { $f->printp(@_) } if $all || $func{printp}; *{"$pkg\::sprintp"} = sub { $f->sprintp(@_) } if $all || $func{sprintp}; $class; } #-------------------- sub addModifiers(@) { my $s = shift; unshift @{$s->{SP_modif}}, @_ } sub encodeFor($) { my ($self, $type) = (shift, shift); defined $type or return $self->{SP_enc} = undef; my %def; if(ref $type eq 'HASH') { %def = %$type; } else { my $def = $predefined_encodings{$type} or die "ERROR: unknown output encoding type $type\n"; %def = (%$def, @_); } my $excls = $def{exclude} || []; my $regexes = join '|', map +(ref $_ eq 'Regexp' ? $_ : qr/(?:^|\.)\Q$_\E$/), ref $excls eq 'ARRAY' ? @$excls : $excls; $def{SP_exclude} = qr/$regexes/o; $self->{SP_enc} = \%def; } sub setDefaults(@) { my $self = shift; my $default = $self->{SP_defs}; my @set = @_==1 && ref $_[0] eq 'HASH' ? %{$_[0]} : @_; while(@set) { my ($modif, $defs) = (shift @set, shift @set); my $was = $defaults{$modif} or die "No defaults available for $modif."; $default->{$modif} = +{ %$was, %$defs }; } $self; } sub defaults($) { $_[0]->{SP_defs}{$_[1]} } #-------------------- #XXX OODoc does not like it when we have methods and functions with the same name. #-------------------- sub sprinti($@) { my ($self, $format) = (shift, shift); my $args = @_==1 ? shift : +{ @_ }; # $args may be a blessed HASH, for instance a Log::Report::Message $args->{_join} //= ', '; local $args->{_format} = $format; my @frags = split /\{([^}]*)\}/, # enforce unicode is_utf8($format) ? $format : decode(latin1 => $format); my @parts; # Code parially duplicated for performance! if(my $enc = $self->{SP_enc}) { my $encode = $enc->{encode}; my $exclude = $enc->{SP_exclude}; push @parts, $encode->($args->{_prepend}) if defined $args->{_prepend}; push @parts, $encode->(shift @frags); while(@frags) { my ($name, $tricks) = (shift @frags) =~ m!^\s*([\pL\p{Pc}\pM][\w.]*)\s*(.*?)\s*$!o or die $format; push @parts, $name =~ $exclude ? $self->_expand($name, $tricks, $args) : $encode->($self->_expand($name, $tricks, $args)); push @parts, $encode->(shift @frags) if @frags; } push @parts, $encode->($args->{_append}) if defined $args->{_append}; } else { push @parts, $args->{_prepend} if defined $args->{_prepend}; push @parts, shift @frags; while(@frags) { (shift @frags) =~ /^\s*([\pL\p{Pc}\pM][\w.]*)\s*(.*?)\s*$/o or die $format; push @parts, $self->_expand($1, $2, $args); push @parts, shift @frags if @frags; } push @parts, $args->{_append} if defined $args->{_append}; } join '', @parts; } sub _expand($$$) { my ($self, $key, $modifier, $args) = @_; local $args->{varname} = $key; my $value; if(index($key, '.') == -1) { # simple value $value = exists $args->{$key} ? $args->{$key} : $self->_missingKey($key, $args); $value = $value->($self, $key, $args) while ref $value eq 'CODE'; } else { my @parts = split /\./, $key; my $key = shift @parts; $value = exists $args->{$key} ? $args->{$key} : $self->_missingKey($key, $args); $value = $value->($self, $key, $args) while ref $value eq 'CODE'; while(defined $value && @parts) { if(blessed $value) { my $method = shift @parts; $value->can($method) or die "object $value cannot $method\n"; $value = $value->$method; # parameters not supported here } elsif(ref $value && reftype $value eq 'HASH') { $value = $value->{shift @parts}; } elsif(index($value, ':') != -1 || $::{$value.'::'}) { my $method = shift @parts; $value->can($method) or die "class $value cannot $method\n"; $value = $value->$method; # parameters not supported here } else { die "not a HASH, object, or class at $parts[0] in $key\n"; } $value = $value->($self, $key, $args) while ref $value eq 'CODE'; } } my $mod; STACKED: while(length $modifier) { my @modif = @{$self->{SP_modif}}; while(@modif) { my ($regex, $callback) = (shift @modif, shift @modif); $modifier =~ s/^($regex)\s*// or next; $value = $callback->($self, $1, $value, $args); next STACKED; } return "{unknown modifier '$modifier'}"; } my $seri = $self->{SP_seri}{defined $value ? ref $value : 'UNDEF'}; $seri ? $seri->($self, $value, $args) : "$value"; } sub _missingKey($$) { my ($self, $key, $args) = @_; $self->{SP_missing}->($self, $key, $args); } sub _reportMissingKey($$) { my ($self, $key, $args) = @_; my $depth = 0; my ($filename, $linenr); while((my $pkg, $filename, $linenr) = caller $depth++) { last unless $pkg->isa(__PACKAGE__) || $pkg->isa('Log::Report::Minimal::Domain'); } warn $self->sprinti( "Missing key '{key}' in format '{format}', file {fn} line {line}\n", key => $key, format => $args->{_format}, fn => $filename, line => $linenr ); undef; } # See dedicated section in explanation in DETAILS sub _modif_format_s($$$$$) { my ($value, $padding, $width, $max, $u) = @_; # String formats like %10s or %-3.5s count characters, not width. # String formats like %10S or %-3.5S are subject to column width. # The latter means: minimal 3 chars, max 5, padding right with blanks. # All inserted strings are upgraded into utf8. my $s = Unicode::GCString->new(is_utf8($value) ? $value : decode(latin1 => $value)); my $pad; if($u eq 'S') { # too large to fit return $value if !$max && $width && $width <= $s->columns; # wider than max. Waiting for $s->trim($max) if $max, see # https://rt.cpan.org/Public/Bug/Display.html?id=84549 $s->substr(-1, 1, '') while $max && $s->columns > $max; $pad = $width ? $width - $s->columns : 0; } else # $u eq 's' { return $value if !$max && $width && $width <= length $s; $s->substr($max, length($s)-$max, '') if $max && length $s > $max; $pad = $width ? $width - length $s : 0; } $pad==0 ? $s->as_string : $padding eq '-' ? $s->as_string . (' ' x $pad) : (' ' x $pad) . $s->as_string; } sub _modif_format_d($$$$) { my ($value, $padding, $max, $sep) = @_; my $d = sprintf "%d", $value; # what perl usually does with floats etc my $v = length $sep ? reverse(reverse($d) =~ s/([0-9][0-9][0-9])/$1$sep/gr) : $d; $v =~ s/^\Q$sep//; if($d !~ /^\-/) { $v = "+$v" if $padding eq '+'; $v = " $v" if $padding eq ' '; } $max or return $v; my $pad = $max - length $v; $pad <= 0 ? $v : $padding eq '-' ? $v . (' ' x $pad) : $padding eq '0' ? ('0' x $pad) . $v : $padding eq '' ? (' ' x $pad) . $v : $v; } sub _modif_format($$$$) { my ($self, $format, $value, $args) = @_; defined $value && length $value or return undef; my $defaults = $self->defaults('FORMAT'); use locale; if(ref $value eq 'ARRAY') { @$value or return '(none)'; return +[ map $self->_format_print($format, $_, $args), @$value ]; } elsif(ref $value eq 'HASH') { keys %$value or return '(none)'; return +{ map +($_ => $self->_format_print($format, $value->{$_}, $args)), keys %$value } ; } $format =~ m/^\%(\-?)([0-9]*)(?:\.([0-9]*))?([sS])$/ ? _modif_format_s($value, $1, $2, $3, $4) : $format =~ m/^\%([+\ \-0]?)([0-9]*)([_,.])?d$/ ? _modif_format_d($value, $1, $2, $3 // $defaults->{thousands}) : return sprintf $format, $value; # simple: standard perl sprintf() } # See dedicated section in explanation in DETAILS sub _modif_bytes($$$) { my ($self, $format, $value, $args) = @_; defined $value && length $value or return undef; return sprintf("%3d B", $value) if $value < 1000; my @scale = qw/kB MB GB TB PB EB ZB/; $value /= 1024; while(@scale > 1 && $value > 999) { shift @scale; $value /= 1024; } return sprintf "%3d$scale[0]", $value + 0.5 if $value > 9.949; sprintf "%3.1f$scale[0]", $value; } sub _modif_html($$$) { my ($self, $format, $value, $args) = @_; defined $value ? (encode_entities $value) : undef; } sub _modif_year($$$) { my ($self, $format, $value, $args) = @_; defined $value or return undef; blessed $value && $value->isa('DateTime') and return $value->year; length $value or return undef; return $1 if $value =~ /^\s*([0-9]{4})\s*$/ && $1 < 2200; my $stamp = $value =~ /^\s*([0-9]+)\s*$/ ? $1 : str2time($value); defined $stamp or return "year not found in '$value'"; strftime "%Y", localtime($stamp); } sub _modif_date($$$) { my ($self, $format, $value, $args) = @_; defined $value or return undef; my $defaults = $self->defaults('DATE'); my $kind = ($format =~ m/^DATE\(([^)]*)\)/ ? $1 : undef) || $defaults->{format}; my $pattern = $date_format{$kind} // $kind; my ($y, $m, $d); if(blessed $value && $value->isa('DateTime')) { ($y, $m, $d) = ($value->year, $value->month, $value->day); } elsif( $value =~ m!^\s*([0-9]{4})[:/.-]([0-9]?[0-9])[:/.-]([0-9]?[0-9])\s*$! || $value =~ m!^\s*([0-9]{4})([0-9][0-9])([0-9][0-9])\s*$!) { ($y, $m, $d) = ($1, $2, $3); } else { my $stamp = $value =~ /\D/ ? str2time($value) : $value; defined $stamp or return "date not found in '$value'"; ($y, $m, $d) = (localtime $stamp)[5, 4, 3]; $y += 1900; $m++; } $pattern =~ s/\%Y/$y/r =~ s/\%m/sprintf "%02d", $m/re =~ s/\%d/sprintf "%02d", $d/re; } sub _modif_time($$$) { my ($self, $format, $value, $args) = @_; defined $value or return undef; blessed $value && $value->isa('DateTime') and return $value->hms; length $value or return undef; return sprintf "%02d:%02d:%02d", $1, $2, $3||0 if $value =~ m!^\s*(0?[0-9]|1[0-9]|2[0-3])\:([0-5]?[0-9])(?:\:([0-5]?[0-9]))?\s*$! || $value =~ m!^\s*(0[0-9]|1[0-9]|2[0-3])([0-5][0-9])(?:([0-5][0-9]))?\s*$!; my $stamp = $value =~ /\D/ ? str2time($value) : $value; defined $stamp or return "time not found in '$value'"; strftime "%H:%M:%S", localtime($stamp); } sub _modif_dt($$$) { my ($self, $format, $value, $args) = @_; defined $value or return undef; blessed $value && $value->isa('DateTime') and $value = $value->epoch; length $value or return undef; my $defaults = $self->defaults('DT'); my $kind = ($format =~ m/^DT\(([^)]*)\)/ ? $1 : undef) || $defaults->{format}; my $pattern = $dt_format{$kind} // $kind; my $stamp = $value =~ /\D/ ? str2time($value) : $value; defined $stamp or return "dt not found in '$value'"; strftime $pattern, localtime($stamp); } sub _modif_undef($$$) { my ($self, $format, $value, $args) = @_; return $value if defined $value && length $value; $format =~ m!//"([^"]*)"|//'([^']*)'|//(\w*)! ? $+ : undef; } sub _modif_name($$$) { my ($self, $format, $value, $args) = @_; "$args->{varname}$format$value"; } sub _modif_chop($$$) { my ($self, $format, $value, $args) = @_; defined $value && length $value or return undef; my $defaults = $self->defaults('CHOP'); $format =~ m/^ CHOP\( ([0-9]+) \,? ([^)]+)? \) | CHOP\b /x or die $format; my $width = $1 // $args->{width} // $defaults->{width}; my $units = $2 // $args->{units} // $defaults->{units}; $width != 0 or return $value; # max width of a char is 2 return $value if 2 * length $value < $width; # surely small enough? my $v = Unicode::GCString->new(is_utf8($value) ? $value : decode(latin1 => $value)); return $value if $width >= $v->columns; # small enough after counting my $head = $defaults->{head}; my $tail = $defaults->{tail}; #XXX This is expensive for long texts, but the value could be filled with many zero-widths my ($shortened, $append) = (0, $head . '+0' . $units . $tail); while($v->columns > $width - length $append) { my $chopped = $v->substr(-1, 1, ''); unless($chopped->length) { # nothing left $append = $head . $shortened . $units . $tail; last; } $chopped->columns > 0 or next; $shortened++; $append = $head . '+' . $shortened . $units . $tail; } # might be one column short my $pad = $v->columns < $width - (length $append) ? ' ' : ''; $v->as_string . $pad . $append; } sub _modif_ellipsis($$$) { my ($self, $format, $value, $args) = @_; defined $value && length $value or return undef; my $defaults = $self->defaults('EL'); $format =~ m/^ EL\( ([0-9]+) \,? ([^)]+)? \) | EL\b /x or die $format; my $width = $1 // $args->{width} // $defaults->{width}; my $replace = $2 // $args->{replace} // $defaults->{replace}; $width != 0 or return $value; # max width of a char is 2 return $value if 2 * length($value) < $width; # surely small enough? my $v = Unicode::GCString->new(is_utf8($value) ? $value : decode(latin1 => $value)); return $value if $width >= $v->columns; # small enough after counting my $r = Unicode::GCString->new(is_utf8($replace) ? $replace : decode(latin1 => $replace)); $r->columns < $width or return $replace; #XXX This is expensive for long texts, but the value could be filled with many zero-widths my $take = $width - $r->columns; $v->substr(-1, 1, '') while $v->columns > $take; # might be one column short my $pad = $v->columns + $r->columns < $width ? ' ' : ''; $v->as_string . $pad . $replace; } sub _modif_unknown($$$) { my ($self, $format, $value, $args) = @_; defined $value or return undef; my $defaults = $self->defaults('UNKNOWN'); $format =~ m/^ UNKNOWN\( ([0-9]+) \) | UNKNOWN\b /x or die $format; $args->{width} = $1 // $args->{width} // $defaults->{width}; return ref $value if blessed $value; my $trim = $args->{trim} // $defaults->{trim}; my $trimmer = $trim eq 'EL' ? '_modif_ellipsis' : $trim eq 'CHOP' ? '_modif_chop' : die $trim; my $shorten = sub { $self->$trimmer($trim, $_[0], $args) }; my $serial = Data::Dumper->new([$value])->Quotekeys(0)->Terse(1)->Useqq(1)->Indent(0)->Sortkeys(1)->Dump; ! reftype $value ? '"' . $shorten->($serial =~ s/^\"//r =~ s/\"$//r) . '"' : reftype $value eq 'ARRAY' ? '[' . $shorten->($serial =~ s/^\[//r =~ s/\]$//r) . ']' : reftype $value eq 'HASH' ? '{' . $shorten->($serial =~ s/^\{//r =~ s/\}$//r) . '}' : $shorten->($serial); } sub printi($$@) { my $self = shift; my $fh = ref $_[0] eq 'GLOB' ? shift : select; $fh->print($self->sprinti(@_)); } sub printp($$@) { my $self = shift; my $fh = ref $_[0] eq 'GLOB' ? shift : select; $fh->print($self->sprintp(@_)); } sub _printp_rewrite($) { my @params = @{$_[0]}; my $printp = $params[0]; my ($printi, @iparam); my ($pos, $maxpos) = (1, 1); while(length $printp) { $printp =~ s/^([^%]*)//s; # take printables $printi .= $1; length $printp or last; if($printp =~ s/^\%\%//) # %% means real % { $printi .= '%'; next; } $printp =~ s/ \% (?:([0-9]+)\$)? # 1=positional ([-+0 \#]*) # 2=flags ([0-9]*|\*)? # 3=width (?:\.([0-9]*|\*))? # 4=precission (?:\{ ([^}]*) \})? # 5=modifiers (\w) # 6=conversion //x or die "format error at '$printp' in '$params[0]'"; $pos = $1 if $1; my $width = !defined $3 ? '' : $3 eq '*' ? $params[$pos++] : $3; my $prec = !defined $4 ? '' : $4 eq '*' ? $params[$pos++] : $4; my $modif = !defined $5 ? '' : $5; my $valpos = $pos++; $maxpos = $pos if $pos > $maxpos; push @iparam, "_$valpos" => $params[$valpos]; my $format = '%'.$2.($width || '').($prec ? ".$prec" : '').$6; $format = '' if $format eq '%s'; my $sep = $modif.$format =~ m/^\w/ ? ' ' : ''; $printi .= "{_$valpos$sep$modif$format}"; } splice @params, 0, $maxpos, @iparam; ($printi, \@params); } sub sprintp(@) { my $self = shift; my ($i, $iparam) = _printp_rewrite \@_; $self->sprinti($i, +{@$iparam}); } #-------------------- 1; String-Print-1.02/lib/String/Print.pod0000644000175000001440000010343315116015372020333 0ustar00markovusers00000000000000=encoding utf8 =head1 NAME String::Print - printf alternative =head1 SYNOPSIS ### 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 =head1 DESCRIPTION This module inserts values into (format) strings. It provides C and C alternatives via both an object oriented and a functional interface. Read in the L chapter below, why this module provides a better alternative for C. Also, some extended B can be found down there. Take a look at them first, when you start using this module! =head1 METHODS See functions L, L, L, and L: 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 When you use this package with functions, then you do not call the constructor explicitly. In that case, these L parameters are added to the C<> line. =over 4 =item $class-EB(%options) The C<%options> of the constructure configure processing options. -Option --Default defaults see modifier docs encode_for undef missing_key modifiers [ qr/^%\S+/ = \&format_printf]> serializers =over 2 =item defaults => \%map [1.00] change the defaults for some modifiers. This is a C<%map> of modifier name to HASH with modifier specific settings. =item encode_for => \%rules|'HTML' [0.91] The format string and the inserted values will get encoded according to some C<%rules>. Function C provided by HTML::Entities is used when you specify the predefined string C. See L and L. =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 C inserted. May can overrule that behavior. =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 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 {'-'} ], encode_for => 'HTML', ); $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-EB(PAIRS) The C 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 L or L. See section L about the details. =item $obj-EB($modifier) [1.00] Returns the current defaults for the C<$modifier>. » example: getting defaults for a modifier my $def = $sp->defaults('EL'); say "Default max width is ", $def->{width}; =item $obj-EB(\%settings|undef|($predefined, %overrule)) [0.91] Enable/define the output encoding. The C<%settings> contain the C CODE and the tag name patterns to C from encoding. Output for C is C<$predefined>, but you may C<%overrule> its settings. Read section L about the details. =item $obj-EB(\%defaults|@defaults) [1.00] Set the defaults for modifiers, either with a HASH where the key modifier name maps to a HASH of settings, or a list of PAIRS. 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); =back =head2 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() =head4 » 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 =head1 FUNCTIONS The functional interface creates a hidden C 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. =head4 » 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 =over 4 =item B( [$fh], $format, %data|\%data ) Calls L to fill the C<%data> into C<$format>, and then sends it to the C<$fh> (by default the selected file handle) open my $fh, '>:encoding(UTF-8)', $file; printi $fh, ... printi \*STDERR, ... =item B( [$fh], $format, @positionals, %options ) Calls L to fill the C<@positionals> in C<$format>, and then sends it to the C<$fh> (by default the selected file handle). =item B($format, %data|\%data|OBJECT, %options) The C<$format> refers to some string, maybe the result of a translation. The C<%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 C<%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 C<$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 C<$format>, without interpolation. This may also be an C which gets stringified, but variables not filled-in. =back =item B($format, @positionals, %options) Where L uses named parameters --especially useful when the strings need translation-- this function stays close to the standard C. 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 C<$format> is rewritten and then fed into L. B with the length of the C<@positionals>: superfluous parameter C<%options> are passed along to C, 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 => ':'; =back =head1 DETAILS Your manual-page reader may not support the unicode used in some of the examples below. =head2 Why use C to replace C? The C 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 uses positional parameters, where L 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 =item pluggable serializers C supports serialization for specific data-types: how to interpolate C, 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 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 implementation will use Unicode::GCString for correct behavior. =item 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. =back =head2 Four components To fill-in a FORMAT, four 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 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. =item 4. encoding Prepare the output for a certain syntax, like HTML. =back Simplified: # 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: 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') =head2 Interpolation: keys A key is a bareword (like a variable name) or a list of barewords separated by dots (no blanks!) B use explanatory key names, to help the translation process once you need that (in the future). =head3 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. =head3 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 C, when C is a HASH it will take the value which belongs to the key C. When C is a CODE, it will run code to get a value. When C is an object, the method C is called to get a value back. When C is a class name, the C refers to an instance method on that class. More examples which do work: # 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. =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. =over 4 =item strings Simple scalar values are interpolated "as is" =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 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 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. 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 C, 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 C<__x()> is the L provided by this module. Internally, it will call C 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 L syntax, shorter but less maintainable: printp "%s %2d %-8s 10d %s\n", '-rw-r--r--', 7, 'me', 12345, $filename; =head3 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; =head4 POSIX modifier extension '%S' The POSIX C does not handle unicode strings. Perl does understand that the 's' modifier may need to insert utf8 so does not count bytes but characters. L does not use characters but "grapheme clusters" via Unicode::GCString. Now, also composed characters do work correctly. Additionally, you can use the B 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; =head4 POSIX modifier extensions '%d' The full pattern is pretty complex: C<< %[+ -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: C<+> will add a '+' sign when positive, 'blank' adds one blank before the digits when positive, a C<0> pads left with zeros instead of blanks. Finally, a C<-> 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 C separator: use String::Print defaults => [ FORMAT => { thousands => ',' } ]; # or my $sp = String::Print->new( defaults => { FORMAT => { thousands => ',' }}, ); # or $sp->setDefaults(FORMAT => { thousands => ',' }); =head3 Modifier: BYTES [0.91] Too often, you have to translate a (file) size into humanly readible format. The C modifier simplifies this a lot: 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". =head3 Modifier: HTML [0.95] interpolate the parameter with HTML entity encoding. =head3 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. The actual treatment of a time value depends on the value. Four different situations: =over 4 =item 1. 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. =item 2. 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 =item 3. 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. =item 4. 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 C<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. =back The output of C is in format 'YYYY', where C