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