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