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 0.102084
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 new
83 format
84 my $result = $formatter->format( $format_string, @input );
85
86 print $formatter->format("My %h is full of %e.\n", 'hovercraft', 'eels');
87
88 This does the actual formatting, calling the methods described above,
89 under "new" and returning the result.
90
91 format_hunker
92 Format hunkers are passed strings and return arrayrefs containing
93 strings (for fixed content) and hashrefs (for formatting code
94 sections).
95
96 The hashref hunks should contain at least two entries: "conversion"
97 for the conversion code (the s, d, or u in %s, %d, or %u); and
98 "literal" for the complete original text of the hunk. For example, a
99 bare minimum hunker should turn the following:
100
101 I would like to buy %d %s today.
102
103 ...into...
104
105 [
106 'I would like to buy ',
107 { conversion => 'd', literal => '%d' },
108 ' ',
109 { conversion => 's', literal => '%d' },
110 ' today.',
111 ]
112
113 Another common entry is "argument". In the format strings expected by
114 "hunk_simply", for example, these are free strings inside of curly
115 braces. These are used extensively other existing helpers for things
116 liked accessing named arguments or providing method names.
117
118 hunk_simply
119 This is the default format hunker. It implements the format string
120 semantics described above.
121
122 This hunker will produce "argument" and "conversion" and "literal".
123 Its other entries are not yet well-defined for public consumption.
124
125 input_processor
126 The input processor is responsible for inspecting the post-format-
127 string arguments, validating them, and returning them in a possibly-
128 transformed form. The processor is passed an arrayref containing the
129 arguments and should return a scalar value to be used as the input
130 going forward.
131
132 return_input
133 This input processor, the default, simply returns the input it was
134 given with no validation or transformation.
135
136 require_named_input
137 This input processor will raise an exception unless there is exactly
138 one post-format-string argument to the format call, and unless that
139 argument is a hashref. It will also replace the arrayref with the
140 given hashref so subsequent phases of the format can avoid lots of
141 needless array dereferencing.
142
143 require_arrayref_input
144 This input processor will raise an exception unless there is exactly
145 one post-format-string argument to the format call, and unless that
146 argument is a arrayref. It will also replace the input with that
147 single arrayref it found so subsequent phases of the format can avoid
148 lots of needless array dereferencing.
149
150 require_single_input
151 This input processor will raise an exception if more than one input is
152 given. After input processing, the single element in the input will be
153 used as the input itself.
154
155 forbid_input
156 This input processor will raise an exception if any input is given. In
157 other words, formatters with this input processor accept format strings
158 and nothing else.
159
160 string_replacer
161 The string_replacer phase is responsible for adding a "replacement"
162 entry to format code hunks. This should be a string-value entry that
163 will be formatted and concatenated into the output string. String
164 replacers can also replace the whole hunk with a string to avoid any
165 subsequent formatting.
166
167 positional_replace
168 This replacer matches inputs to the hunk's position in the format
169 string. This is the default replacer, used in the synopsis, above,
170 which should make its behavior clear. At present, fixed-string
171 conversions do not affect the position of arg matched, meaning that
172 given the following:
173
174 my $formatter = String::Formatter->new({
175 codes => {
176 f => 'fixed string',
177 s => sub { ... },
178 }
179 });
180
181 $formatter->format("%s %f %s", 1, 2);
182
183 The subroutine is called twice, once for the input 1 and once for the
184 input 2. This behavior may change after some more experimental use.
185
186 named_replace
187 This replacer should be used with the "require_named_input" input
188 processor. It expects the input to be a hashref and it finds values to
189 be interpolated by looking in the hashref for the brace-enclosed name
190 on each format code. Here's an example use:
191
192 $formatter->format("This was the %{adj}s day in %{num}d weeks.", {
193 adj => 'best',
194 num => 6,
195 });
196
197 indexed_replace
198 This replacer should be used with the "require_arrayref_input" input
199 processor. It expects the input to be an arrayref and it finds values
200 to be interpolated by looking in the arrayref for the brace-enclosed
201 index on each format code. Here's an example use:
202
203 $formatter->format("This was the %{1}s day in %{0}d weeks.", [ 6, 'best' ]);
204
205 method_replace
206 This string replacer method expects the input to be a single value on
207 which methods can be called. If a value was given in braces to the
208 format code, it is passed as an argument.
209
210 keyed_replace
211 This string replacer method expects the input to be a single hashref.
212 Coderef code values are used as callbacks, but strings are used as hash
213 keys. If a value was given in braces to the format code, it is
214 ignored.
215
216 For example if the codes contain "i => 'ident'" then %i in the format
217 string will be replaced with "$input->{ident}" in the output.
218
219 hunk_formatter
220 The hunk_formatter processes each the hashref hunks left after string
221 replacement and returns a string. When it is called, it is passed a
222 hunk hashref and must return a string.
223
224 format_simply
225 This is the default hunk formatter. It deals with minimum and maximum
226 width cues as well as left and right alignment. Beyond that, it does
227 no formatting of the replacement string.
228
230 Format strings are generally assumed to look like Perl's sprintf's
231 format strings:
232
233 There's a bunch of normal strings and then %s format %1.4c with %% signs.
234
235 The exact semantics of the format codes are not totally settled yet --
236 and they can be replaced on a per-formatter basis. Right now, they're
237 mostly a subset of Perl's astonishingly large and complex system. That
238 subset looks like this:
239
240 % - a percent sign to begin the format
241 ... - (optional) various modifiers to the format like "-5" or "#" or "2$"
242 {..} - (optional) a string inside braces
243 s - a short string (usually one character) identifying the conversion
244
245 Not all format modifiers found in Perl's "sprintf" are yet supported.
246 Currently the only format modifiers must match:
247
248 (-)? # left-align, rather than right
249 (\d*)? # (optional) minimum field width
250 (?:\.(\d*))? # (optional) maximum field width
251
252 Some additional format semantics may be added, but probably nothing
253 exotic. Even things like "2$" and "*" are probably not going to appear
254 in String::Formatter's default behavior.
255
256 Another subtle difference, introduced intentionally, is in the handling
257 of "%%". With the default String::Formatter behavior, string "%%" is
258 not interpreted as a formatting code. This is different from the
259 behavior of Perl's "sprintf", which interprets it as a special
260 formatting character that doesn't consume input and always acts like
261 the fixed string "%". The upshot of this is:
262
263 sprintf "%%"; # ==> returns "%"
264 stringf "%%"; # ==> returns "%%"
265
266 sprintf "%10%"; # ==> returns " %"
267 stringf "%10%"; # ==> dies: unknown format code %
268
269 my $formatter = String::Formatter->new({
270 codes => { ... },
271 format_hunker => ...,
272 input_processor => ...,
273 string_replacer => ...,
274 hunk_formatter => ...,
275 });
276
277 This returns a new formatter. The "codes" argument contains the
278 formatting codes for the formatter in the form:
279
280 codes => {
281 s => 'fixed string',
282 S => 'different string',
283 c => sub { ... },
284 }
285
286 Code values (or "conversions") should either be strings or coderefs.
287 This hashref can be accessed later with the "codes" method.
288
289 The other four arguments change how the formatting occurs. Formatting
290 happens in five phases:
291
292 1. format_hunker - format string is broken down into fixed and %-code
293 hunks
294
295 2. input_processor - the other inputs are validated and processed
296
297 3. string_replacer - replacement strings are generated by using
298 conversions
299
300 4. hunk_formatter - replacement strings in hunks are formatted
301
302 5. all hunks, now strings, are recombined; this phase is just "join"
303
304 The defaults are found by calling "default_WHATEVER" for each helper
305 that isn't given. Values must be either strings (which are interpreted
306 as method names) or coderefs. The semantics for each method are
307 described in the methods' sections, below.
308
310 String::Formatter is based on String::Format, written by Darren
311 Chamberlain. For a history of the code, check the project's source
312 code repository. All bugs should be reported to Ricardo Signes and
313 String::Formatter. Very little of the original code remains.
314
316 · Ricardo Signes <rjbs@cpan.org>
317
318 · Darren Chamberlain <darren@cpan.org>
319
321 This software is Copyright (c) 2013 by Ricardo Signes <rjbs@cpan.org>.
322
323 This is free software, licensed under:
324
325 The GNU General Public License, Version 2, June 1991
326
327
328
329perl v5.30.0 2019-07-26 String::Formatter(3)