home *** CD-ROM | disk | FTP | other *** search
/ RISC DISC 2 / RISC_DISC_2.iso / pd_share / utilities / cli / perl / !Perl / Manual / perlform < prev    next >
Encoding:
Text File  |  1995-04-18  |  15.1 KB  |  317 lines

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