home *** CD-ROM | disk | FTP | other *** search
/ Acorn User 10 / AU_CD10.iso / Updates / Perl / Non-RPC / Docs / perlform < prev    next >
Text File  |  1999-04-17  |  15KB  |  373 lines

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