This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Use PERL=../miniperl
[perl5.git] / pod / perlform.pod
1 =head1 NAME
2
3 perlform - Perl formats
4
5 =head1 DESCRIPTION
6
7 Perl has a mechanism to help you generate simple reports and charts.  To
8 facilitate this, Perl helps you lay out your output page in your code in a
9 fashion that's close to how it will look when it's printed.  It can keep
10 track of things like how many lines on a page, what page you're, when to
11 print page headers, etc.  Keywords are borrowed from FORTRAN:
12 format() to declare and write() to execute; see their entries in
13 L<perlfunc>.  Fortunately, the layout is much more legible, more like
14 BASIC's PRINT USING statement.  Think of it as a poor man's nroff(1).
15
16 Formats, like packages and subroutines, are declared rather than executed,
17 so they may occur at any point in your program.  (Usually it's best to
18 keep them all together though.) They have their own namespace apart from
19 all the other "types" in Perl.  This means that if you have a function
20 named "Foo", it is not the same thing as having a format named "Foo".
21 However, the default name for the format associated with a given
22 filehandle is the same as the name of the filehandle.  Thus, the default
23 format for STDOUT is name "STDOUT", and the default format for filehandle
24 TEMP is name "TEMP".  They just look the same.  They aren't.
25
26 Output record formats are declared as follows:
27
28     format NAME =
29     FORMLIST
30     .
31
32 If name is omitted, format "STDOUT" is defined.  FORMLIST consists of a
33 sequence of lines, each of which may be of one of three types:
34
35 =over 4
36
37 =item 1.
38
39 A comment, indicated by putting a '#' in the first column.
40
41 =item 2.
42
43 A "picture" line giving the format for one output line.
44
45 =item 3.
46
47 An argument line supplying values to plug into the previous picture line.
48
49 =back
50
51 Picture lines are printed exactly as they look, except for certain fields
52 that substitute values into the line.  Each field in a picture line starts
53 with either "@" (at) or "^" (caret).  These lines do not undergo any kind
54 of variable interpolation.  The at field (not to be confused with the array
55 marker @) is the normal kind of field; the other kind, caret fields, are used
56 to do rudimentary multi-line text block filling.  The length of the field
57 is supplied by padding out the field with multiple "<", ">", or "|"
58 characters to specify, respectively, left justification, right
59 justification, or centering.  If the variable would exceed the width
60 specified, it is truncated.
61
62 As an alternate form of right justification, you may also use "#"
63 characters (with an optional ".") to specify a numeric field.  This way
64 you can line up the decimal points.  If any value supplied for these
65 fields contains a newline, only the text up to the newline is printed.
66 Finally, the special field "@*" can be used for printing multi-line,
67 non-truncated values; it should appear by itself on a line.
68
69 The values are specified on the following line in the same order as
70 the picture fields.  The expressions providing the values should be
71 separated by commas.  The expressions are all evaluated in a list context
72 before the line is processed, so a single list expression could produce
73 multiple list elements.  The expressions may be spread out to more than
74 one line if enclosed in braces.  If so, the opening brace must be the first
75 token on the first line.
76
77 Picture fields that begin with ^ rather than @ are treated specially.
78 With a # field, the field is blanked out if the value is undefined.  For
79 other field types, the caret enables a kind of fill mode.  Instead of an
80 arbitrary expression, the value supplied must be a scalar variable name
81 that contains a text string.  Perl puts as much text as it can into the
82 field, and then chops off the front of the string so that the next time
83 the variable is referenced, more of the text can be printed.  (Yes, this
84 means that the variable itself is altered during execution of the write()
85 call, and is not returned.)  Normally you would use a sequence of fields
86 in a vertical stack to print out a block of text.  You might wish to end
87 the final field with the text "...", which will appear in the output if
88 the text was too long to appear in its entirety.  You can change which
89 characters 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
91 list of the desired characters.
92
93 Using caret fields can produce variable length records.  If the text
94 to be formatted is short, you can suppress blank lines by putting a
95 "~" (tilde) character anywhere in the line.  The tilde will be translated
96 to a space upon output.  If you put a second tilde contiguous to the
97 first, the line will be repeated until all the fields on the line are
98 exhausted.  (If you use a field of the at variety, the expression you
99 supply had better not give the same value every time forever!)
100
101 Top-of-form processing is by default handled by a format with the 
102 same name as the current filehandle with "_TOP" concatenated to it.
103 It's triggered at the top of each page.  See <perlfunc/write()>.
104
105 Examples:
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
149 It is possible to intermix print()s with write()s on the same output
150 channel, but you'll have to handle $- ($FORMAT_LINES_LEFT)
151 yourself.
152
153 =head2 Format Variables
154
155 The current format name is stored in the variable C<$~> ($FORMAT_NAME),
156 and the current top of form format name is in C<$^> ($FORMAT_TOP_NAME).
157 The current output page number is stored in C<$%> ($FORMAT_PAGE_NUMBER),
158 and the number of lines on the page is in C<$=> ($FORMAT_LINES_PER_PAGE).
159 Whether to autoflush output on this handle is stored in C<$|>
160 ($OUTPUT_AUTOFLUSH).  The string output before each top of page (except
161 the first) is stored in C<$^L> ($FORMAT_FORMFEED).  These variables are
162 set on a per-filehandle basis, so you'll need to select() into a different
163 one to affect them:
164
165     select((select(OUTF), 
166             $~ = "My_Other_Format",
167             $^ = "My_Top_Format"
168            )[0]);
169
170 Pretty ugly, eh?  It's a common idiom though, so don't be too surprised
171 when you see it.  You can at least use a temporary variable to hold
172 the previous filehandle: (this is a much better approach in general,
173 because not only does legibility improve, you now have intermediary
174 stage 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
181 If 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
189 But you still have those funny select()s.  So just use the FileHandle
190 module.  Now, you can access these special variables using lower-case
191 method names instead:
192
193     use FileHandle;
194     format_name     OUTF "My_Other_Format";
195     format_top_name OUTF "My_Top_Format";
196
197 Much better!
198
199 =head1 NOTES
200
201 Since the values line may contain arbitrary expressions (for at fields, 
202 not caret fields), you can farm out more sophisticated processing
203 to other functions, like sprintf() or one of your own.  For example:
204
205     format Ident = 
206         @<<<<<<<<<<<<<<<
207         &commify($n)
208     .
209
210 To get a real at or caret into the field, do this:
211
212     format Ident = 
213     I have an @ here.
214             "@"
215     .
216
217 To center a whole line of text, do something like this:
218
219     format Ident = 
220     @|||||||||||||||||||||||||||||||||||||||||||||||
221             "Some text line"
222     .
223
224 There is no builtin way to say "float this to the right hand side
225 of the page, however wide it is."  You have to specify where it goes.
226 The truly desperate can generate their own format on the fly, based
227 on 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
239 Which would generate a format looking something like this:
240
241  format STDOUT = 
242  ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
243  $entry
244          ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
245  $entry
246  .
247
248 Here'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
264 While $FORMAT_TOP_NAME contains the name of the current header format,
265 there is no corresponding mechanism to automatically do the same thing
266 for a footer.  Not knowing how big a format is going to be until you
267 evaluate it is one of the major problems.  It's on the TODO list.
268
269 Here's one strategy:  If you have a fixed-size footer, you can get footers
270 by checking $FORMAT_LINES_LEFT before each write() and print the footer
271 yourself if necessary.
272
273 Here's another strategy; open a pipe to yourself, using C<open(MESELF, "|-")> 
274 (see L<perlfunc/open()>) and always write() to MESELF instead of
275 STDOUT.  Have your child process postprocesses its STDIN to rearrange
276 headers and footers however you like.  Not very convenient, but doable.
277
278 =head2 Accessing Formatting Internals
279
280 For low-level access to the formatting mechanism.  you may use formline()
281 and access C<$^A> (the $ACCUMULATOR variable) directly.
282
283 For 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
291 Or to make an swrite() subroutine which is to write() what sprintf()
292 is to printf(), do this:
293
294     use Carp;
295     sub swrite {
296         croak "usage: swrite PICTURE ARGS" unless @_;
297         my $format = shift;
298         $^A = "";
299         formline($format,@_);
300         return $^A;
301     } 
302
303     $string = swrite(<<'END', 1, 2, 3);
304  Check me out
305  @<<<  @|||  @>>>
306  END
307     print $string;
308
309 =head1 WARNING
310
311 Lexical variables (declared with "my") are not visible within a
312 format unless the format is declared within the scope of the lexical
313 variable.  (They weren't visible at all before version 5.001.)  Furthermore,
314 lexical aliases will not be compiled correctly: see
315 L<perlfunc/my> for other issues.