next up previous contents
Next: Field Lines Up: Reports Previous: Reports

Format Statements

Perl uses formats as guidelines when writing report information. A format is used to tell Perl what static text is needed and where variable information should be placed. Formats are defined by using the format statement. The syntax for the format statement is format

format FORMATNAME =

    FIELD_LINE

    VALUE_LINE

The FORMATNAME is usually the same name as the file handle that is used to accept the report output.

If you don't specify a FORMATNAME, Perl uses STDOUT. The FIELD_LINE part of the format statement consists of text and field holders. A field holder represents a given line width that Perl will fill with the value of a variable. The VALUE_LINE line consists of a comma-delimited list of expressions used to fill the field holders in FIELD_LINE.

Report headings, which appear at the top of each page, have the following format: format

FORMATNAME_TOP =
    FIELD_LINE
    VALUE_LINE

Yes, the only difference between a detail line and a heading is that _TOP is appended to the FORMATNAME.

NoteThe location of format statements is unimportant because they define only a format and never are executed. I feel that they should appear either at the beginning of a program or the end of a program, rarely in the middle. Placing format statements in the middle of your program might make them hard to find when they need to be changed. Of course, you should be consistent where you place them.

A typical format statement might look like this:

format =

    The total amount is $@###.##

                         $total

The at character @ is used to start a field holder. In this example, the field holder is seven characters long (the at sign and decimal point count, as well as the pound signs #). The next section, "Example: Using Field Lines," goes into more detail about field lines and field holders.

Format statements are used only when invoked by the write() function. The write() function takes only one parameter: a file handle to send output to. Like many things in Perl, if no parameter is specified, a default is provided. In this case, STDOUT will be used when no FORMATNAME is specified. In order to use the preceding format, you simply assign a value to $total and then call the write() function. For example (total.pl):

$total = 243.45

write();

$total = 50.00

write();

These lines will display:

    The total amount is $  243.45

    The total amount is $   50.50

The output will be sent to STDOUT. Notice that the decimal points are automatically lined up when the lines are displayed.


next up previous contents
Next: Field Lines Up: Reports Previous: Reports
dave@cs.cf.ac.uk