This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perl5.001 patch.1e
[perl5.git] / pod / perlform.pod
CommitLineData
a0d0e21e
LW
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 lay out your output page in your code in a
9fashion that's close to how it will look when it's printed. It can keep
10track of things like how many lines on a page, what page you're, when to
748a9306 11print page headers, etc. Keywords are borrowed from FORTRAN:
a0d0e21e 12format() to declare and write() to execute; see their entries in
748a9306 13L<perlfunc>. Fortunately, the layout is much more legible, more like
a0d0e21e
LW
14BASIC's PRINT USING statement. Think of it as a poor man's nroff(1).
15
16Formats, like packages and subroutines, are declared rather than executed,
17so they may occur at any point in your program. (Usually it's best to
18keep them all together though.) They have their own namespace apart from
19all the other "types" in Perl. This means that if you have a function
20named "Foo", it is not the same thing as having a format named "Foo".
21However, 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 name "STDOUT", and the default format for filehandle
24TEMP is name "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 name is omitted, format "STDOUT" is defined. FORMLIST consists of a
33sequence of lines, each of which may be of one of three types:
34
35=over 4
36
37=item 1.
38
39A comment, indicated by putting a '#' in the first column.
40
41=item 2.
42
43A "picture" line giving the format for one output line.
44
45=item 3.
46
47An argument line supplying values to plug into the previous picture line.
48
49=back
50
51Picture lines are printed exactly as they look, except for certain fields
52that substitute values into the line. Each field in a picture line starts
53with either "@" (at) or "^" (caret). These lines do not undergo any kind
54of variable interpolation. The at field (not to be confused with the array
55marker @) is the normal kind of field; the other kind, caret fields, are used
56to do rudimentary multi-line text block filling. The length of the field
57is supplied by padding out the field with multiple "<", ">", or "|"
58characters to specify, respectively, left justification, right
59justification, or centering. If the variable would exceed the width
60specified, it is truncated.
61
62As an alternate form of right justification, you may also use "#"
63characters (with an optional ".") to specify a numeric field. This way
64you can line up the decimal points. If any value supplied for these
65fields contains a newline, only the text up to the newline is printed.
66Finally, the special field "@*" can be used for printing multi-line,
67non-truncated values; it should appear by itself on a line.
68
69The values are specified on the following line in the same order as
70the picture fields. The expressions providing the values should be
71separated by commas. The expressions are all evaluated in a list context
72before the line is processed, so a single list expression could produce
73multiple list elements. The expressions may be spread out to more than
74one line if enclosed in braces. If so, the opening brace must be the first
75token on the first line.
76
77Picture fields that begin with ^ rather than @ are treated specially.
78With a # field, the field is blanked out if the value is undefined. For
79other field types, the caret enables a kind of fill mode. Instead of an
80arbitrary expression, the value supplied must be a scalar variable name
81that contains a text string. Perl puts as much text as it can into the
82field, and then chops off the front of the string so that the next time
83the variable is referenced, more of the text can be printed. (Yes, this
84means that the variable itself is altered during execution of the write()
85call, and is not returned.) Normally you would use a sequence of fields
86in a vertical stack to print out a block of text. You might wish to end
87the final field with the text "...", which will appear in the output if
88the text was too long to appear in its entirety. You can change which
89characters are legal to break on by changing the variable C<$:> (that's
90$FORMAT_LINE_BREAK_CHARACTERS if you're using the English module) to a
91list of the desired characters.
92
748a9306 93Using caret fields can produce variable length records. If the text
a0d0e21e
LW
94to be formatted is short, you can suppress blank lines by putting a
95"~" (tilde) character anywhere in the line. The tilde will be translated
96to a space upon output. If you put a second tilde contiguous to the
97first, the line will be repeated until all the fields on the line are
98exhausted. (If you use a field of the at variety, the expression you
99supply had better not give the same value every time forever!)
100
101Top-of-form processing is by default handled by a format with the
102same name as the current filehandle with "_TOP" concatenated to it.
103It's triggered at the top of each page. See <perlfunc/write()>.
104
105Examples:
106
107 # a report on the /etc/passwd file
108 format STDOUT_TOP =
109 Passwd File
110 Name Login Office Uid Gid Home
111 ------------------------------------------------------------------
112 .
113 format STDOUT =
114 @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
115 $name, $login, $office,$uid,$gid, $home
116 .
117
118
119 # a report from a bug report form
120 format STDOUT_TOP =
121 Bug Reports
122 @<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
123 $system, $%, $date
124 ------------------------------------------------------------------
125 .
126 format STDOUT =
127 Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
128 $subject
129 Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
130 $index, $description
131 Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
132 $priority, $date, $description
133 From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
134 $from, $description
135 Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
136 $programmer, $description
137 ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
138 $description
139 ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
140 $description
141 ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
142 $description
143 ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
144 $description
145 ~ ^<<<<<<<<<<<<<<<<<<<<<<<...
146 $description
147 .
148
149It is possible to intermix print()s with write()s on the same output
150channel, but you'll have to handle $- ($FORMAT_LINES_LEFT)
151yourself.
152
153=head2 Format Variables
154
155The current format name is stored in the variable C<$~> ($FORMAT_NAME),
156and the current top of form format name is in C<$^> ($FORMAT_TOP_NAME).
157The current output page number is stored in C<$%> ($FORMAT_PAGE_NUMBER),
158and the number of lines on the page is in C<$=> ($FORMAT_LINES_PER_PAGE).
748a9306 159Whether to autoflush output on this handle is stored in C<$|>
a0d0e21e
LW
160($OUTPUT_AUTOFLUSH). The string output before each top of page (except
161the first) is stored in C<$^L> ($FORMAT_FORMFEED). These variables are
162set on a per-filehandle basis, so you'll need to select() into a different
163one to affect them:
164
165 select((select(OUTF),
166 $~ = "My_Other_Format",
167 $^ = "My_Top_Format"
168 )[0]);
169
170Pretty ugly, eh? It's a common idiom though, so don't be too surprised
171when you see it. You can at least use a temporary variable to hold
172the previous filehandle: (this is a much better approach in general,
173because not only does legibility improve, you now have intermediary
174stage in the expression to single-step the debugger through):
175
176 $ofh = select(OUTF);
177 $~ = "My_Other_Format";
178 $^ = "My_Top_Format";
179 select($ofh);
180
181If you use the English module, you can even read the variable names:
182
183 use English;
184 $ofh = select(OUTF);
185 $FORMAT_NAME = "My_Other_Format";
186 $FORMAT_TOP_NAME = "My_Top_Format";
187 select($ofh);
188
189But you still have those funny select()s. So just use the FileHandle
190module. Now, you can access these special variables using lower-case
191method names instead:
192
193 use FileHandle;
194 format_name OUTF "My_Other_Format";
195 format_top_name OUTF "My_Top_Format";
196
197Much better!
198
199=head1 NOTES
200
748a9306
LW
201Since the values line may contain arbitrary expressions (for at fields,
202not caret fields), you can farm out more sophisticated processing
a0d0e21e
LW
203to other functions, like sprintf() or one of your own. For example:
204
205 format Ident =
206 @<<<<<<<<<<<<<<<
207 &commify($n)
208 .
209
210To get a real at or caret into the field, do this:
211
212 format Ident =
213 I have an @ here.
214 "@"
215 .
216
217To center a whole line of text, do something like this:
218
219 format Ident =
220 @|||||||||||||||||||||||||||||||||||||||||||||||
221 "Some text line"
222 .
223
224There is no builtin way to say "float this to the right hand side
225of the page, however wide it is." You have to specify where it goes.
226The truly desperate can generate their own format on the fly, based
227on the current number of columns, and then eval() it:
228
229 $format = "format STDOUT = \n";
230 . '^' . '<' x $cols . "\n";
231 . '$entry' . "\n";
232 . "\t^" . "<" x ($cols-8) . "~~\n";
233 . '$entry' . "\n";
234 . ".\n";
235 print $format if $Debugging;
236 eval $format;
237 die $@ if $@;
238
239Which would generate a format looking something like this:
240
241 format STDOUT =
242 ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
243 $entry
244 ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
245 $entry
246 .
247
248Here's a little program that's somewhat like fmt(1):
249
250 format =
251 ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~
252 $_
253
254 .
255
256 $/ = '';
257 while (<>) {
258 s/\s*\n\s*/ /g;
259 write;
260 }
261
262=head2 Footers
263
264While $FORMAT_TOP_NAME contains the name of the current header format,
265there is no corresponding mechanism to automatically do the same thing
266for a footer. Not knowing how big a format is going to be until you
267evaluate it is one of the major problems. It's on the TODO list.
268
269Here's one strategy: If you have a fixed-size footer, you can get footers
270by checking $FORMAT_LINES_LEFT before each write() and print the footer
271yourself if necessary.
272
273Here's another strategy; open a pipe to yourself, using C<open(MESELF, "|-")>
274(see L<perlfunc/open()>) and always write() to MESELF instead of
275STDOUT. Have your child process postprocesses its STDIN to rearrange
276headers and footers however you like. Not very convenient, but doable.
277
278=head2 Accessing Formatting Internals
279
280For low-level access to the formatting mechanism. you may use formline()
281and access C<$^A> (the $ACCUMULATOR variable) directly.
282
283For example:
284
285 $str = formline <<'END', 1,2,3;
286 @<<< @||| @>>>
287 END
288
289 print "Wow, I just stored `$^A' in the accumulator!\n";
290
291Or to make an swrite() subroutine which is to write() what sprintf()
292is to printf(), do this:
293
a0d0e21e
LW
294 use Carp;
295 sub swrite {
748a9306
LW
296 croak "usage: swrite PICTURE ARGS" unless @_;
297 my $format = shift;
298 $^A = "";
299 formline($format,@_);
300 return $^A;
a0d0e21e
LW
301 }
302
303 $string = swrite(<<'END', 1, 2, 3);
304 Check me out
305 @<<< @||| @>>>
306 END
307 print $string;
308
309=head1 WARNING
310
748a9306
LW
311Lexical variables (declared with "my") are not visible within a
312format unless the format is declared within the scope of the lexical
313variable. (They weren't visiblie at all before version 5.001.)