1PERLFORM(1) Perl Programmers Reference Guide PERLFORM(1)
2
3
4
6 perlform - Perl formats
7
9 Perl has a mechanism to help you generate simple reports and charts.
10 To facilitate this, Perl helps you code up your output page close to
11 how it will look when it's printed. It can keep track of things like
12 how many lines are on a page, what page you're on, when to print page
13 headers, etc. Keywords are borrowed from FORTRAN: format() to declare
14 and write() to execute; see their entries in perlfunc. Fortunately,
15 the layout is much more legible, more like BASIC's PRINT USING
16 statement. Think of it as a poor man's nroff(1).
17
18 Formats, like packages and subroutines, are declared rather than
19 executed, so they may occur at any point in your program. (Usually
20 it's best to keep them all together though.) They have their own
21 namespace apart from all the other "types" in Perl. This means that if
22 you have a function named "Foo", it is not the same thing as having a
23 format named "Foo". However, the default name for the format
24 associated with a given filehandle is the same as the name of the
25 filehandle. Thus, the default format for STDOUT is named "STDOUT", and
26 the default format for filehandle TEMP is named "TEMP". They just look
27 the same. They aren't.
28
29 Output record formats are declared as follows:
30
31 format NAME =
32 FORMLIST
33 .
34
35 If the name is omitted, format "STDOUT" is defined. A single "." in
36 column 1 is used to terminate a format. FORMLIST consists of a
37 sequence of lines, each of which may be one of three types:
38
39 1. A comment, indicated by putting a '#' in the first column.
40
41 2. A "picture" line giving the format for one output line.
42
43 3. An argument line supplying values to plug into the previous picture
44 line.
45
46 Picture lines contain output field definitions, intermingled with
47 literal text. These lines do not undergo any kind of variable
48 interpolation. Field definitions are made up from a set of characters,
49 for starting and extending a field to its desired width. This is the
50 complete set of characters for field definitions:
51
52 @ start of regular field
53 ^ start of special field
54 < pad character for left justification
55 | pad character for centering
56 > pad character for right justification
57 # pad character for a right-justified numeric field
58 0 instead of first #: pad number with leading zeroes
59 . decimal point within a numeric field
60 ... terminate a text field, show "..." as truncation evidence
61 @* variable width field for a multi-line value
62 ^* variable width field for next line of a multi-line value
63 ~ suppress line with all fields empty
64 ~~ repeat line until all fields are exhausted
65
66 Each field in a picture line starts with either "@" (at) or "^"
67 (caret), indicating what we'll call, respectively, a "regular" or
68 "special" field. The choice of pad characters determines whether a
69 field is textual or numeric. The tilde operators are not part of a
70 field. Let's look at the various possibilities in detail.
71
72 Text Fields
73 The length of the field is supplied by padding out the field with
74 multiple "<", ">", or "|" characters to specify a non-numeric field
75 with, respectively, left justification, right justification, or
76 centering. For a regular field, the value (up to the first newline) is
77 taken and printed according to the selected justification, truncating
78 excess characters. If you terminate a text field with "...", three
79 dots will be shown if the value is truncated. A special text field may
80 be used to do rudimentary multi-line text block filling; see "Using
81 Fill Mode" for details.
82
83 Example:
84 format STDOUT =
85 @<<<<<< @|||||| @>>>>>>
86 "left", "middle", "right"
87 .
88 Output:
89 left middle right
90
91 Numeric Fields
92 Using "#" as a padding character specifies a numeric field, with right
93 justification. An optional "." defines the position of the decimal
94 point. With a "0" (zero) instead of the first "#", the formatted number
95 will be padded with leading zeroes if necessary. A special numeric
96 field is blanked out if the value is undefined. If the resulting value
97 would exceed the width specified the field is filled with "#" as
98 overflow evidence.
99
100 Example:
101 format STDOUT =
102 @### @.### @##.### @### @### ^####
103 42, 3.1415, undef, 0, 10000, undef
104 .
105 Output:
106 42 3.142 0.000 0 ####
107
108 The Field @* for Variable-Width Multi-Line Text
109 The field "@*" can be used for printing multi-line, nontruncated
110 values; it should (but need not) appear by itself on a line. A final
111 line feed is chomped off, but all other characters are emitted
112 verbatim.
113
114 The Field ^* for Variable-Width One-line-at-a-time Text
115 Like "@*", this is a variable-width field. The value supplied must be a
116 scalar variable. Perl puts the first line (up to the first "\n") of the
117 text into the field, and then chops off the front of the string so that
118 the next time the variable is referenced, more of the text can be
119 printed. The variable will not be restored.
120
121 Example:
122 $text = "line 1\nline 2\nline 3";
123 format STDOUT =
124 Text: ^*
125 $text
126 ~~ ^*
127 $text
128 .
129 Output:
130 Text: line 1
131 line 2
132 line 3
133
134 Specifying Values
135 The values are specified on the following format line in the same order
136 as the picture fields. The expressions providing the values must be
137 separated by commas. They are all evaluated in a list context before
138 the line is processed, so a single list expression could produce
139 multiple list elements. The expressions may be spread out to more than
140 one line if enclosed in braces. If so, the opening brace must be the
141 first token on the first line. If an expression evaluates to a number
142 with a decimal part, and if the corresponding picture specifies that
143 the decimal part should appear in the output (that is, any picture
144 except multiple "#" characters without an embedded "."), the character
145 used for the decimal point is determined by the current LC_NUMERIC
146 locale if "use locale" is in effect. This means that, if, for example,
147 the run-time environment happens to specify a German locale, "," will
148 be used instead of the default ".". See perllocale and "WARNINGS" for
149 more information.
150
151 Using Fill Mode
152 On text fields the caret enables a kind of fill mode. Instead of an
153 arbitrary expression, the value supplied must be a scalar variable that
154 contains a text string. Perl puts the next portion of the text into
155 the field, and then chops off the front of the string so that the next
156 time the variable is referenced, more of the text can be printed.
157 (Yes, this means that the variable itself is altered during execution
158 of the write() call, and is not restored.) The next portion of text is
159 determined by a crude line-breaking algorithm. You may use the carriage
160 return character ("\r") to force a line break. You can change which
161 characters are legal to break on by changing the variable $: (that's
162 $FORMAT_LINE_BREAK_CHARACTERS if you're using the English module) to a
163 list of the desired characters.
164
165 Normally you would use a sequence of fields in a vertical stack
166 associated with the same scalar variable to print out a block of text.
167 You might wish to end the final field with the text "...", which will
168 appear in the output if the text was too long to appear in its
169 entirety.
170
171 Suppressing Lines Where All Fields Are Void
172 Using caret fields can produce lines where all fields are blank. You
173 can suppress such lines by putting a "~" (tilde) character anywhere in
174 the line. The tilde will be translated to a space upon output.
175
176 Repeating Format Lines
177 If you put two contiguous tilde characters "~~" anywhere into a line,
178 the line will be repeated until all the fields on the line are
179 exhausted, i.e. undefined. For special (caret) text fields this will
180 occur sooner or later, but if you use a text field of the at variety,
181 the expression you supply had better not give the same value every
182 time forever! ("shift(@f)" is a simple example that would work.) Don't
183 use a regular (at) numeric field in such lines, because it will never
184 go blank.
185
186 Top of Form Processing
187 Top-of-form processing is by default handled by a format with the same
188 name as the current filehandle with "_TOP" concatenated to it. It's
189 triggered at the top of each page. See "write" in perlfunc.
190
191 Examples:
192
193 # a report on the /etc/passwd file
194 format STDOUT_TOP =
195 Passwd File
196 Name Login Office Uid Gid Home
197 ------------------------------------------------------------------
198 .
199 format STDOUT =
200 @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
201 $name, $login, $office,$uid,$gid, $home
202 .
203
204
205 # a report from a bug report form
206 format STDOUT_TOP =
207 Bug Reports
208 @<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
209 $system, $%, $date
210 ------------------------------------------------------------------
211 .
212 format STDOUT =
213 Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
214 $subject
215 Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
216 $index, $description
217 Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
218 $priority, $date, $description
219 From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
220 $from, $description
221 Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
222 $programmer, $description
223 ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
224 $description
225 ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
226 $description
227 ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
228 $description
229 ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
230 $description
231 ~ ^<<<<<<<<<<<<<<<<<<<<<<<...
232 $description
233 .
234
235 It is possible to intermix print()s with write()s on the same output
236 channel, but you'll have to handle "$-" ($FORMAT_LINES_LEFT) yourself.
237
238 Format Variables
239 The current format name is stored in the variable $~ ($FORMAT_NAME),
240 and the current top of form format name is in $^ ($FORMAT_TOP_NAME).
241 The current output page number is stored in $% ($FORMAT_PAGE_NUMBER),
242 and the number of lines on the page is in $= ($FORMAT_LINES_PER_PAGE).
243 Whether to autoflush output on this handle is stored in $|
244 ($OUTPUT_AUTOFLUSH). The string output before each top of page (except
245 the first) is stored in $^L ($FORMAT_FORMFEED). These variables are
246 set on a per-filehandle basis, so you'll need to select() into a
247 different one to affect them:
248
249 select((select(OUTF),
250 $~ = "My_Other_Format",
251 $^ = "My_Top_Format"
252 )[0]);
253
254 Pretty ugly, eh? It's a common idiom though, so don't be too surprised
255 when you see it. You can at least use a temporary variable to hold the
256 previous filehandle: (this is a much better approach in general,
257 because not only does legibility improve, you now have an intermediary
258 stage in the expression to single-step the debugger through):
259
260 $ofh = select(OUTF);
261 $~ = "My_Other_Format";
262 $^ = "My_Top_Format";
263 select($ofh);
264
265 If you use the English module, you can even read the variable names:
266
267 use English;
268 $ofh = select(OUTF);
269 $FORMAT_NAME = "My_Other_Format";
270 $FORMAT_TOP_NAME = "My_Top_Format";
271 select($ofh);
272
273 But you still have those funny select()s. So just use the FileHandle
274 module. Now, you can access these special variables using lowercase
275 method names instead:
276
277 use FileHandle;
278 format_name OUTF "My_Other_Format";
279 format_top_name OUTF "My_Top_Format";
280
281 Much better!
282
284 Because the values line may contain arbitrary expressions (for at
285 fields, not caret fields), you can farm out more sophisticated
286 processing to other functions, like sprintf() or one of your own. For
287 example:
288
289 format Ident =
290 @<<<<<<<<<<<<<<<
291 &commify($n)
292 .
293
294 To get a real at or caret into the field, do this:
295
296 format Ident =
297 I have an @ here.
298 "@"
299 .
300
301 To center a whole line of text, do something like this:
302
303 format Ident =
304 @|||||||||||||||||||||||||||||||||||||||||||||||
305 "Some text line"
306 .
307
308 There is no builtin way to say "float this to the right hand side of
309 the page, however wide it is." You have to specify where it goes. The
310 truly desperate can generate their own format on the fly, based on the
311 current number of columns, and then eval() it:
312
313 $format = "format STDOUT = \n"
314 . '^' . '<' x $cols . "\n"
315 . '$entry' . "\n"
316 . "\t^" . "<" x ($cols-8) . "~~\n"
317 . '$entry' . "\n"
318 . ".\n";
319 print $format if $Debugging;
320 eval $format;
321 die $@ if $@;
322
323 Which would generate a format looking something like this:
324
325 format STDOUT =
326 ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
327 $entry
328 ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
329 $entry
330 .
331
332 Here's a little program that's somewhat like fmt(1):
333
334 format =
335 ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~
336 $_
337
338 .
339
340 $/ = '';
341 while (<>) {
342 s/\s*\n\s*/ /g;
343 write;
344 }
345
346 Footers
347 While $FORMAT_TOP_NAME contains the name of the current header format,
348 there is no corresponding mechanism to automatically do the same thing
349 for a footer. Not knowing how big a format is going to be until you
350 evaluate it is one of the major problems. It's on the TODO list.
351
352 Here's one strategy: If you have a fixed-size footer, you can get
353 footers by checking $FORMAT_LINES_LEFT before each write() and print
354 the footer yourself if necessary.
355
356 Here's another strategy: Open a pipe to yourself, using "open(MYSELF,
357 "|-")" (see "open" in perlfunc) and always write() to MYSELF instead of
358 STDOUT. Have your child process massage its STDIN to rearrange headers
359 and footers however you like. Not very convenient, but doable.
360
361 Accessing Formatting Internals
362 For low-level access to the formatting mechanism, you may use
363 formline() and access $^A (the $ACCUMULATOR variable) directly.
364
365 For example:
366
367 $str = formline <<'END', 1,2,3;
368 @<<< @||| @>>>
369 END
370
371 print "Wow, I just stored '$^A' in the accumulator!\n";
372
373 Or to make an swrite() subroutine, which is to write() what sprintf()
374 is to printf(), do this:
375
376 use Carp;
377 sub swrite {
378 croak "usage: swrite PICTURE ARGS" unless @_;
379 my $format = shift;
380 $^A = "";
381 formline($format,@_);
382 return $^A;
383 }
384
385 $string = swrite(<<'END', 1, 2, 3);
386 Check me out
387 @<<< @||| @>>>
388 END
389 print $string;
390
392 The lone dot that ends a format can also prematurely end a mail message
393 passing through a misconfigured Internet mailer (and based on
394 experience, such misconfiguration is the rule, not the exception). So
395 when sending format code through mail, you should indent it so that the
396 format-ending dot is not on the left margin; this will prevent SMTP
397 cutoff.
398
399 Lexical variables (declared with "my") are not visible within a format
400 unless the format is declared within the scope of the lexical variable.
401
402 If a program's environment specifies an LC_NUMERIC locale and "use
403 locale" is in effect when the format is declared, the locale is used to
404 specify the decimal point character in formatted output. Formatted
405 output cannot be controlled by "use locale" at the time when write() is
406 called. See perllocale for further discussion of locale handling.
407
408 Within strings that are to be displayed in a fixed-length text field,
409 each control character is substituted by a space. (But remember the
410 special meaning of "\r" when using fill mode.) This is done to avoid
411 misalignment when control characters "disappear" on some output media.
412
413
414
415perl v5.30.1 2019-11-29 PERLFORM(1)