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