home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 2 / AACD 2.iso / AACD / Programming / perlman / man / perlform.txt < prev    next >
Encoding:
Text File  |  1999-09-09  |  13.4 KB  |  335 lines

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