1String::Formatter(3) User Contributed Perl Documentation String::Formatter(3)
2
3
4
6 String::Formatter - build sprintf-like functions of your own
7
9 version 1.235
10
12 use String::Formatter stringf => {
13 -as => 'str_rf',
14 codes => {
15 f => sub { $_ },
16 b => sub { scalar reverse $_ },
17 o => 'Okay?',
18 },
19 };
20
21 print str_rf('This is %10f and this is %-15b, %o', 'forward', 'backward');
22
23 ...prints...
24
25 This is forward and this is drawkcab , okay?
26
28 String::Formatter is a tool for building sprintf-like formatting
29 routines. It supports named or positional formatting, custom
30 conversions, fixed string interpolation, and simple width-matching out
31 of the box. It is easy to alter its behavior to write new kinds of
32 format string expanders. For most cases, it should be easy to build
33 all sorts of formatters out of the options built into
34 String::Formatter.
35
36 Normally, String::Formatter will be used to import a sprintf-like
37 routine referred to as ""stringf"", but which can be given any name you
38 like. This routine acts like sprintf in that it takes a string and
39 some inputs and returns a new string:
40
41 my $output = stringf "Some %a format %s for you to %u.\n", { ... };
42
43 This routine is actually a wrapper around a String::Formatter object
44 created by importing stringf. In the following code, the entire
45 hashref after "stringf" is passed to String::Formatter's constructor
46 (the "new" method), save for the "-as" key and any other keys that
47 start with a dash.
48
49 use String::Formatter
50 stringf => {
51 -as => 'fmt_time',
52 codes => { ... },
53 format_hunker => ...,
54 input_processor => ...,
55 },
56 stringf => {
57 -as => 'fmt_date',
58 codes => { ... },
59 string_replacer => ...,
60 hunk_formatter => ...,
61 },
62 ;
63
64 As you can see, this will generate two stringf routines, with different
65 behaviors, which are installed with different names. Since the
66 behavior of these routines is based on the "format" method of a
67 String::Formatter object, the rest of the documentation will describe
68 the way the object behaves.
69
70 There's also a "named_stringf" export, which behaves just like the
71 "stringf" export, but defaults to the "named_replace" and
72 "require_named_input" arguments. There's a "method_stringf" export,
73 which defaults "method_replace" and "require_single_input". Finally, a
74 "indexed_stringf", which defaults to "indexed_replaced" and
75 "require_arrayref_input". For more on these, keep reading, and check
76 out the cookbook.
77
78 String::Formatter::Cookbook provides a number of recipes for ways to
79 put String::Formatter to use.
80
82 This library should run on perls released even a long time ago. It
83 should work on any version of perl released in the last five years.
84
85 Although it may work on older versions of perl, no guarantee is made
86 that the minimum required version will not be increased. The version
87 may be increased for any reason, and there is no promise that patches
88 will be accepted to lower the minimum required perl.
89
91 new
92 my $formatter = String::Formatter->new({
93 codes => { ... },
94 format_hunker => ...,
95 input_processor => ...,
96 string_replacer => ...,
97 hunk_formatter => ...,
98 });
99
100 This returns a new formatter. The "codes" argument contains the
101 formatting codes for the formatter in the form:
102
103 codes => {
104 s => 'fixed string',
105 S => 'different string',
106 c => sub { ... },
107 }
108
109 Code values (or "conversions") should either be strings or coderefs.
110 This hashref can be accessed later with the "codes" method.
111
112 The other four arguments change how the formatting occurs. Formatting
113 happens in five phases:
114
115 1. format_hunker - format string is broken down into fixed and %-code
116 hunks
117
118 2. input_processor - the other inputs are validated and processed
119
120 3. string_replacer - replacement strings are generated by using
121 conversions
122
123 4. hunk_formatter - replacement strings in hunks are formatted
124
125 5. all hunks, now strings, are recombined; this phase is just "join"
126
127 The defaults are found by calling "default_WHATEVER" for each helper
128 that isn't given. Values must be either strings (which are interpreted
129 as method names) or coderefs. The semantics for each method are
130 described in the methods' sections, below.
131
132 format
133 my $result = $formatter->format( $format_string, @input );
134
135 print $formatter->format("My %h is full of %e.\n", 'hovercraft', 'eels');
136
137 This does the actual formatting, calling the methods described above,
138 under "new" and returning the result.
139
140 format_hunker
141 Format hunkers are passed strings and return arrayrefs containing
142 strings (for fixed content) and hashrefs (for formatting code
143 sections).
144
145 The hashref hunks should contain at least two entries: "conversion"
146 for the conversion code (the s, d, or u in %s, %d, or %u); and
147 "literal" for the complete original text of the hunk. For example, a
148 bare minimum hunker should turn the following:
149
150 I would like to buy %d %s today.
151
152 ...into...
153
154 [
155 'I would like to buy ',
156 { conversion => 'd', literal => '%d' },
157 ' ',
158 { conversion => 's', literal => '%d' },
159 ' today.',
160 ]
161
162 Another common entry is "argument". In the format strings expected by
163 "hunk_simply", for example, these are free strings inside of curly
164 braces. These are used extensively other existing helpers for things
165 liked accessing named arguments or providing method names.
166
167 hunk_simply
168 This is the default format hunker. It implements the format string
169 semantics described above.
170
171 This hunker will produce "argument" and "conversion" and "literal".
172 Its other entries are not yet well-defined for public consumption.
173
174 input_processor
175 The input processor is responsible for inspecting the post-format-
176 string arguments, validating them, and returning them in a possibly-
177 transformed form. The processor is passed an arrayref containing the
178 arguments and should return a scalar value to be used as the input
179 going forward.
180
181 return_input
182 This input processor, the default, simply returns the input it was
183 given with no validation or transformation.
184
185 require_named_input
186 This input processor will raise an exception unless there is exactly
187 one post-format-string argument to the format call, and unless that
188 argument is a hashref. It will also replace the arrayref with the
189 given hashref so subsequent phases of the format can avoid lots of
190 needless array dereferencing.
191
192 require_arrayref_input
193 This input processor will raise an exception unless there is exactly
194 one post-format-string argument to the format call, and unless that
195 argument is a arrayref. It will also replace the input with that
196 single arrayref it found so subsequent phases of the format can avoid
197 lots of needless array dereferencing.
198
199 require_single_input
200 This input processor will raise an exception if more than one input is
201 given. After input processing, the single element in the input will be
202 used as the input itself.
203
204 forbid_input
205 This input processor will raise an exception if any input is given. In
206 other words, formatters with this input processor accept format strings
207 and nothing else.
208
209 string_replacer
210 The string_replacer phase is responsible for adding a "replacement"
211 entry to format code hunks. This should be a string-value entry that
212 will be formatted and concatenated into the output string. String
213 replacers can also replace the whole hunk with a string to avoid any
214 subsequent formatting.
215
216 positional_replace
217 This replacer matches inputs to the hunk's position in the format
218 string. This is the default replacer, used in the synopsis, above,
219 which should make its behavior clear. At present, fixed-string
220 conversions do not affect the position of arg matched, meaning that
221 given the following:
222
223 my $formatter = String::Formatter->new({
224 codes => {
225 f => 'fixed string',
226 s => sub { ... },
227 }
228 });
229
230 $formatter->format("%s %f %s", 1, 2);
231
232 The subroutine is called twice, once for the input 1 and once for the
233 input 2. This behavior may change after some more experimental use.
234
235 named_replace
236 This replacer should be used with the "require_named_input" input
237 processor. It expects the input to be a hashref and it finds values to
238 be interpolated by looking in the hashref for the brace-enclosed name
239 on each format code. Here's an example use:
240
241 $formatter->format("This was the %{adj}s day in %{num}d weeks.", {
242 adj => 'best',
243 num => 6,
244 });
245
246 indexed_replace
247 This replacer should be used with the "require_arrayref_input" input
248 processor. It expects the input to be an arrayref and it finds values
249 to be interpolated by looking in the arrayref for the brace-enclosed
250 index on each format code. Here's an example use:
251
252 $formatter->format("This was the %{1}s day in %{0}d weeks.", [ 6, 'best' ]);
253
254 method_replace
255 This string replacer method expects the input to be a single value on
256 which methods can be called. If a value was given in braces to the
257 format code, it is passed as an argument.
258
259 keyed_replace
260 This string replacer method expects the input to be a single hashref.
261 Coderef code values are used as callbacks, but strings are used as hash
262 keys. If a value was given in braces to the format code, it is
263 ignored.
264
265 For example if the codes contain "i => 'ident'" then %i in the format
266 string will be replaced with "$input->{ident}" in the output.
267
268 hunk_formatter
269 The hunk_formatter processes each the hashref hunks left after string
270 replacement and returns a string. When it is called, it is passed a
271 hunk hashref and must return a string.
272
273 format_simply
274 This is the default hunk formatter. It deals with minimum and maximum
275 width cues as well as left and right alignment. Beyond that, it does
276 no formatting of the replacement string.
277
279 Format strings are generally assumed to look like Perl's sprintf's
280 format strings:
281
282 There's a bunch of normal strings and then %s format %1.4c with %% signs.
283
284 The exact semantics of the format codes are not totally settled yet --
285 and they can be replaced on a per-formatter basis. Right now, they're
286 mostly a subset of Perl's astonishingly large and complex system. That
287 subset looks like this:
288
289 % - a percent sign to begin the format
290 ... - (optional) various modifiers to the format like "-5" or "#" or "2$"
291 {..} - (optional) a string inside braces
292 s - a short string (usually one character) identifying the conversion
293
294 Not all format modifiers found in Perl's "sprintf" are yet supported.
295 Currently the only format modifiers must match:
296
297 (-)? # left-align, rather than right
298 (\d*)? # (optional) minimum field width
299 (?:\.(\d*))? # (optional) maximum field width
300
301 Some additional format semantics may be added, but probably nothing
302 exotic. Even things like "2$" and "*" are probably not going to appear
303 in String::Formatter's default behavior.
304
305 Another subtle difference, introduced intentionally, is in the handling
306 of "%%". With the default String::Formatter behavior, string "%%" is
307 not interpreted as a formatting code. This is different from the
308 behavior of Perl's "sprintf", which interprets it as a special
309 formatting character that doesn't consume input and always acts like
310 the fixed string "%". The upshot of this is:
311
312 sprintf "%%"; # ==> returns "%"
313 stringf "%%"; # ==> returns "%%"
314
315 sprintf "%10%"; # ==> returns " %"
316 stringf "%10%"; # ==> dies: unknown format code %
317
319 String::Formatter is based on String::Format, written by Darren
320 Chamberlain. For a history of the code, check the project's source
321 code repository. All bugs should be reported to Ricardo Signes and
322 String::Formatter. Very little of the original code remains.
323
325 • Ricardo Signes <cpan@semiotic.systems>
326
327 • Darren Chamberlain <darren@cpan.org>
328
330 • Darren Chamberlain <dlc@sevenroot.org>
331
332 • David Steinbrunner <dsteinbrunner@pobox.com>
333
334 • dlc <dlc>
335
336 • Ricardo Signes <rjbs@semiotic.systems>
337
339 This software is Copyright (c) 2022 by Ricardo Signes
340 <cpan@semiotic.systems>.
341
342 This is free software, licensed under:
343
344 The GNU General Public License, Version 2, June 1991
345
346
347
348perl v5.38.0 2023-07-21 String::Formatter(3)