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