home *** CD-ROM | disk | FTP | other *** search
/ H4CK3R 14 / hacker14.iso / programacao / visual / perl.exe / {app} / Library / Perl / tutorial.pod < prev   
Encoding:
Text File  |  2002-10-01  |  21.6 KB  |  556 lines

  1. =head1 A Brief Perltidy Tutorial
  2.  
  3. Perltidy can save you a lot of tedious editing if you spend a few
  4. minutes learning to use it effectively.  Perltidy is highly
  5. configurable, but for many programmers the default parameter set will be
  6. satisfactory, with perhaps a few additional parameters to account for
  7. style preferences.
  8.  
  9. This tutorial assumes that perltidy has been installed on your system.
  10. Installation instructions accompany the package.  To follow along with
  11. this tutorial, please find a small Perl script and place a copy in a
  12. temporary directory.  For example, here is a small (and silly) script:
  13.  
  14.  print "Help Desk -- What Editor do you use?";
  15.  chomp($editor = <STDIN>);
  16.  if ($editor =~ /emacs/i) {
  17.    print "Why aren't you using vi?\n";
  18.  } elsif ($editor =~ /vi/i) {
  19.    print "Why aren't you using emacs?\n";
  20.  } else {
  21.    print "I think that's the problem\n";
  22.  }
  23.  
  24. It is included in the F<docs> section of the distribution.
  25.  
  26. =head2 A First Test
  27.  
  28. Assume that the name of your script is F<testfile.pl>.  You can reformat it
  29. with the default options to use the style recommended in the perlstyle man
  30. pages with the command:
  31.  
  32.  perltidy testfile.pl
  33.  
  34. For safety, perltidy never overwrites your original file.  In this case,
  35. its output will go to a file named F<testfile.pl.tdy>, which you should
  36. examine now with your editor.  Here is what the above file looks like
  37. with the default options:
  38.  
  39.  print "Help Desk -- What Editor do you use?";
  40.  chomp( $editor = <STDIN> );
  41.  if ( $editor =~ /emacs/i ) {
  42.      print "Why aren't you using vi?\n";
  43.  }
  44.  elsif ( $editor =~ /vi/i ) {
  45.      print "Why aren't you using emacs?\n";
  46.  }
  47.  else {
  48.      print "I think that's the problem\n";
  49.  }
  50.  
  51. You'll notice an immediate style change from the "cuddled-else" style of
  52. the original to the default "non-cuddled-else" style.  This is because
  53. perltidy has to make some kind of default selection of formatting
  54. options, and this default tries to follow the suggestions in the
  55. perlstyle man pages.  
  56.  
  57. If you prefer the original "cuddled-else" style, don't worry, you can
  58. indicate that with a B<-ce> flag.  So if you rerun with that flag
  59.  
  60.  perltidy -ce testfile.pl
  61.  
  62. you will see a return to the original "cuddled-else" style.  There are
  63. many more parameters for controlling style, and some of the most useful
  64. of these are discussed below.  
  65.  
  66. =head2 Indentation
  67.  
  68. Another noticeable difference between the original and the reformatted
  69. file is that the indentation has been changed from 2 spaces to 4 spaces.
  70. That's because 4 spaces is the default.  You may change this to be a
  71. different number with B<-i=n>.
  72.  
  73. To get some practice, try these examples, and examine the resulting
  74. F<testfile.pl.tdy> file:
  75.  
  76.  perltidy -i=8 testfile.pl
  77.  
  78. This changes the default of 4 spaces per indentation level to be 8.  Now
  79. just to emphasize the point, try this and examine the result:
  80.  
  81.  perltidy -i=0 testfile.pl
  82.  
  83. There will be no indentation at all in this case.
  84.  
  85. =head2 Input Flags
  86.  
  87. This is a good place to mention a few points regarding the input flags.
  88. First, for each option, there are two forms, a long form and a short
  89. form, and either may be used.  
  90.  
  91. For example, if you want to change the number of columns corresponding to one
  92. indentation level to 3 (from the default of 4) you may use either
  93.  
  94.  -i=3   or  --indent-columns=3
  95.  
  96. The short forms are convenient for entering parameters by hand, whereas
  97. the long forms, though often ridiculously long, are self-documenting and
  98. therefore useful in configuration scripts.  You may use either one or
  99. two dashes ahead of the parameters.  Also, the '=' sign is optional, 
  100. and may be a single space instead.  However, the value of a parameter
  101. must NOT be adjacent to the flag, like this B<-i3> (WRONG).  Also,
  102. flags must be input separately, never bundled together.
  103.  
  104. =head2 Line Length and Continuation Indentation.
  105.  
  106. If you change the indentation spaces you will probably also need to
  107. change the continuation indentation spaces with the parameter B<-ci=n>.
  108. The continuation indentation is the extra indentation -- 2 spaces by
  109. default -- given to that portion of a long line which has been placed
  110. below the start of a statement.  For example:
  111.  
  112.  croak "Couldn't pop genome file"
  113.    unless sysread( $impl->{file}, $element, $impl->{group} )
  114.    and truncate( $impl->{file}, $new_end );
  115.  
  116. There is no fixed rule for setting the value for B<-ci=n>, but it should
  117. probably not exceed one-half of the number of spaces of a full
  118. indentation level.
  119.  
  120. In the above snippet, the statement was broken into three lines.  The
  121. actual number is governed by a parameter, the maximum line length, as
  122. well as by what perltidy considers to be good break points.  The maximum
  123. line length is 80 characters by default.  You can change this to be any
  124. number B<n> with the B<-l=n> flag.  Perltidy tries to produce lines
  125. which do not exceed this length, and it does this by finding good break
  126. points.  For example, the above snippet would look like this with
  127. B<perltidy -l=40>:
  128.  
  129.  croak "Couldn't pop genome file"
  130.    unless sysread(
  131.      $impl->{file}, $element,
  132.      $impl->{group}
  133.    )
  134.    and truncate( $impl->{file},
  135.      $new_end );
  136.  
  137. =head2 Tabs or Spaces?
  138.  
  139. With indentation, there is always a tab issue to resolve.  By default,
  140. perltidy will use leading ascii space characters instead of tabs.  The
  141. reason is that this will be displayed correctly by virtually all
  142. editors, and in the long run, will avoid maintenance problems.  
  143.  
  144. However, if you prefer, you may have perltidy entab the leading
  145. whitespace of a line with the command B<-et=n>, where B<n> is the number
  146. of spaces which will be represented by one tab.  But note that your text
  147. will not be displayed properly unless viewed with software that is
  148. configured to display B<n> spaces per tab.
  149.  
  150. =head2 Input/Output Control
  151.  
  152. In the first example, we saw that if we pass perltidy the name
  153. of a file on the command line, it reformats it and creates a
  154. new filename by appending an extension, F<.tdy>.  This is the
  155. default behavior, but there are several other options.
  156.  
  157. On most systems, you may use wildcards to reformat a whole batch of
  158. files at once, like this for example:
  159.  
  160.  perltidy *.pl
  161.  
  162. and in this case, each of the output files will be have a name equal to
  163. the input file with the extension F<.tdy> appended.  If you decide that
  164. the formatting is acceptable, you will want to backup your originals and
  165. then remove the F<.tdy> extensions from the reformatted files.  There is
  166. an powerful perl script called C<rename> that can be used for this
  167. purpose; if you don't have it, you can find it for example in B<The Perl
  168. Cookbook>.
  169.  
  170. If you find that the formatting done by perltidy is usually acceptable,
  171. you may want to save some effort by letting perltidy do a simple backup
  172. of the original files and then reformat them in place.  You specify this
  173. with a B<-b> flag.  For example, the command
  174.  
  175.  perltidy -b *.pl
  176.  
  177. will rename the original files by appending a F<.bak> extension, and then
  178. create reformatted files with the same names as the originals.  (If you don't
  179. like the default backup extension choice F<.bak>, the manual tells how to
  180. change it).  Each time you run perltidy with the B<-b> option, the previous
  181. F<.bak> files will be overwritten, so please make regular separate backups.
  182.  
  183. If there is no input filename specified on the command line, then input
  184. is assumed to come from standard input and output will go to standard
  185. output.  On systems with a Unix-like interface, you can use perltidy as
  186. a filter, like this:
  187.  
  188.  perltidy <somefile.pl >newfile.pl
  189.  
  190. What happens in this case is that the shell takes care of the redirected
  191. input files, '<somefile.pl', and so perltidy never sees the filename.
  192. Therefore, it knows to use the standard input and standard output
  193. channels.
  194.  
  195. If you are executing perltidy on a file and want to force the output
  196. to standard output, rather than create a F<.tdy> file, you can
  197. indicate this with the flag B<-st>, like this:
  198.  
  199.  perltidy somefile.pl -st >otherfile.pl
  200.  
  201. You can also control the name of the output file with the B<-o> flag,
  202. like this:
  203.  
  204.  perltidy testfile.pl -o=testfile.new.pl
  205.  
  206. =head2 Style Variations
  207.  
  208. Perltidy has to make some kind of default selection of formatting
  209. options, and its choice is to try to follow the suggestions in the
  210. perlstyle man pages.  Many programmers more or less follow these
  211. suggestions with a few exceptions.  In this section we will
  212. look at just a few of the most commonly used style parameters.  Later,
  213. you may want to systematically develop a set of style
  214. parameters with the help of
  215. the perltidy B<stylekey> web page at
  216. http://perltidy.sourceforge.net/stylekey.html
  217.  
  218. =over 4
  219.  
  220. =item B<-ce>, cuddled elses
  221.  
  222. If you prefer cuddled elses, use the B<-ce> flag.  
  223.  
  224. =item B<-bl>, braces left
  225.  
  226. Here is what the C<if> block in the above script looks like with B<-bl>:
  227.  
  228.  if ( $editor =~ /emacs/i )
  229.  {
  230.      print "Why aren't you using vi?\n";
  231.  }
  232.  elsif ( $editor =~ /vi/i )
  233.  {
  234.      print "Why aren't you using emacs?\n";
  235.  }
  236.  else
  237.  {
  238.      print "I think that's the problem\n";
  239.  }
  240.  
  241. =item B<-lp>, Lining up with parentheses
  242.  
  243. The B<-lp> parameter can enhance the readability of lists by adding
  244. extra indentation.  Consider:
  245.  
  246.         %romanNumerals = (
  247.             one   => 'I',
  248.             two   => 'II',
  249.             three => 'III',
  250.             four  => 'IV',
  251.             five  => 'V',
  252.             six   => 'VI',
  253.             seven => 'VII',
  254.             eight => 'VIII',
  255.             nine  => 'IX',
  256.             ten   => 'X'
  257.         );
  258.  
  259. With the B<-lp> flag, this is formatted as:
  260.  
  261.         %romanNumerals = (
  262.                            one   => 'I',
  263.                            two   => 'II',
  264.                            three => 'III',
  265.                            four  => 'IV',
  266.                            five  => 'V',
  267.                            six   => 'VI',
  268.                            seven => 'VII',
  269.                            eight => 'VIII',
  270.                            nine  => 'IX',
  271.                            ten   => 'X'
  272.                            );
  273.  
  274. which is preferred by some.
  275.  
  276. =item B<-bt>,B<-pt>,B<-sbt>:  Container tightness
  277.  
  278. These are parameters for controlling the amount of space within
  279. containing parentheses, braces, and square brackets.  The example below
  280. shows the effect of the three possible values, 0, 1, and 2, for the case
  281. of parentheses:
  282.  
  283.  if ( ( my $len_tab = length( $tabstr ) ) > 0 ) {  # -pt=0
  284.  if ( ( my $len_tab = length($tabstr) ) > 0 ) {    # -pt=1 (default)
  285.  if ((my $len_tab = length($tabstr)) > 0) {        # -pt=2
  286.  
  287. A value of 0 causes all parens to be padded on the inside with a space,
  288. and a value of 2 causes this never to happen.  With a value of 1, spaces
  289. will be introduced if the item within is more than a single token.
  290.  
  291. =back
  292.  
  293. =head2 Configuration Files
  294.  
  295. While style preferences vary, most people would agree that it is
  296. important to maintain a uniform style within a script, and this is a
  297. major benefit provided by perltidy.  Once you have decided on which, if
  298. any, special options you prefer, you may want to avoid having to enter
  299. them each time you run it.  You can do this by creating a special file
  300. named F<.perltidyrc> in either your home directory, your current
  301. directory, or certain system-dependent locations.  (Note the leading "."
  302. in the file name).  
  303.  
  304. A handy command to know when you start using a configuration file is
  305.  
  306.   perltidy -dpro
  307.  
  308. which will dump to standard output the search that perltidy makes when
  309. looking for a configuration file, and the contents of the one that it
  310. selects, if any.  This is one of a number of useful "dump and die"
  311. commands, in which perltidy will dump some information to standard
  312. output and then immediately exit.  Others include B<-h>, which dumps
  313. help information, and B<-v>, which dumps the version number.
  314.  
  315. Another useful command when working with configuration files is
  316.  
  317.  perltidy -pro=file
  318.  
  319. which causes the contents of F<file> to be used as the configuration
  320. file instead of a F<.perltidyrc> file.  With this command, you can
  321. easily switch among several different candidate configuration files
  322. during testing.
  323.  
  324. This F<.perltidyrc> file is free format.  It is simply a list of
  325. parameters, just as they would be entered on a command line.  Any number
  326. of lines may be used, with any number of parameters per line, although
  327. it may be easiest to read with one parameter per line.  Blank lines are
  328. ignored, and text after a '#' is ignored to the end of a line.
  329.  
  330. Here is an example of a F<.perltidyrc> file:
  331.  
  332.   # This is a simple of a .perltidyrc configuration file
  333.   # This implements a highly spaced style
  334.   -bl     # braces on new lines
  335.   -pt=0  # parens not tight at all
  336.   -bt=0  # braces not tight
  337.   -sbt=0 # square brackets not tight
  338.  
  339. If you experiment with this file, remember that it is in your directory,
  340. since if you are running on a Unix system, files beginning with a "."
  341. are normally hidden.  
  342.  
  343. If you have a F<.perltidyrc> file, and want perltidy to ignore it,
  344. use the B<-npro> flag on the command line.
  345.  
  346. =head2 Error Reporting
  347.  
  348. Let's run through a 'fire drill' to see how perltidy reports errors.  Try
  349. introducing an extra opening brace somewhere in a test file.  For example,
  350. introducing an extra brace in the file listed above produces the following
  351. message on the terminal (or standard error output):
  352.  
  353.  Please see file testfile.pl.ERR!
  354.  
  355. Here is what F<testfile.pl.ERR> contains:
  356.  
  357.  10:    final indentation level: 1
  358.  
  359.  Final nesting depth of '{'s is 1
  360.  The most recent un-matched '{' is on line 6
  361.  6: } elsif ($temperature < 68) {{
  362.                                 ^
  363.  
  364. This shows how perltidy will, by default, write error messages to a file
  365. with the extension F<.ERR>, and it will write a note that it did so to
  366. the standard error device.  If you would prefer to have the error
  367. messages sent to standard output, instead of to a F<.ERR> file, use the
  368. B<-se> flag.
  369.  
  370. Almost every programmer would want to see error messages of this type,
  371. but there are a number of messages which, if reported, would be
  372. annoying.  To manage this problem, perltidy puts its messages into two
  373. categories: errors and warnings.  The default is to just report the
  374. errors, but you can control this with input flags, as follows:
  375.  
  376.  flag  what this does
  377.  ----  --------------
  378.        default: report errors but not warnings
  379.  -w    report all errors and warnings
  380.  -q    quiet! do not report either errors or warnings
  381.  
  382. The default is generally a good choice, but it's not a bad idea to check
  383. programs with B<-w> occasionally, especially if your are looking for a
  384. bug.  For example, it will ask if you really want '=' instead of '=~' in
  385. this line:
  386.   
  387.     $line = s/^\s*//;
  388.  
  389. This kind of error can otherwise be hard to find.
  390.  
  391. =head2 Syntax Checking
  392.  
  393. Perltidy will normally try to check itself by running C<perl -c> on both
  394. the input and output files.  If the input file has good syntax but the
  395. output file has bad syntax, then perltidy made an error.  This is very
  396. unlikely, but worth checking.  
  397.  
  398. Here's a diagram showing how this works:
  399.  
  400.                           OK                            OK
  401.      check input file ---------->  check output file ---------> ok
  402.              |                            |
  403.              | Fail                       | Fail
  404.              |                            |
  405.        -w shows errors             perltidy made error
  406.  
  407. If the input file has an error according to the C<perl -c> check, then
  408. the output file will not be checked (since we already know that it will
  409. have an error), and any error messages returned by the C<perl -c> check
  410. will be discarded (because they usually turn out to be more annoying
  411. than helpful).  If you want to see them, though, you can use the B<-w>
  412. flag.  This might be useful if you are debugging a script.
  413.  
  414. This syntax check will be deactivated for Windows 9x/Me and also when
  415. input or output are not from identifiable filenames.  Perltidy will, of
  416. course, still report any syntax errors that it detects by itself in
  417. these cases.  
  418.  
  419. =head2 The Log File
  420.  
  421. One last topic that needs to be touched upon concerns the F<.LOG> file.
  422. This is where perltidy records messages that are not normally of any
  423. interest, but which just might occasionally be useful.  This file is not
  424. saved, though, unless perltidy detects that it has made a mistake or you
  425. ask for it to be saved.
  426.  
  427. There are a couple of ways to ask perltidy to save a log file.  To
  428. create a relatively sparse log file, use
  429.  
  430.  perltidy -log testfile.pl
  431.  
  432. and for a verbose log file, use
  433.  
  434.  perltidy -g testfile.pl
  435.  
  436. The difference is that the first form only saves detailed information at
  437. least every 50th line, while the second form saves detailed information
  438. about every line.
  439.  
  440. So returning to our example, lets force perltidy to save a
  441. verbose log file by issuing the following command
  442.  
  443.  perltidy -g testfile.pl
  444.  
  445. You will find that a file named F<testfile.pl.LOG> has been
  446. created in your directory.  
  447.  
  448. If you open this file, you will see that it is a text file with a
  449. combination of warning messages and informative messages.  All you need
  450. to know for now is that it exists; someday it may be useful.
  451.  
  452. =head2 Using Perltidy as a Filter on Selected Text from an Editor
  453.  
  454. Most programmer's editors allow a selected group of lines to be passed
  455. through an external filter.  Perltidy has been designed to work well as
  456. a filter, and it is well worthwhile learning the appropriate commands to
  457. do this with your editor.  This means that you can enter a few
  458. keystrokes and watch a block of text get reformatted.  If you are not
  459. doing this, you are missing out of a lot of fun!  You may want to supply
  460. the B<-q> flag to prevent error messages regarding incorrect syntax,
  461. since errors may be obvious in the indentation of the reformatted text.
  462. This is entirely optional, but if you do not use the B<-q> flag, you
  463. will need to use the undo keys in case an error message appears on the
  464. screen. 
  465.  
  466. For example, within the B<vim> editor it is only necessary to select the
  467. text by any of the text selection methods, and then issue the command
  468. !perltidy in command mode.  Thus, an entire file can be formatted using
  469.  
  470.  :%!perltidy -q
  471.  
  472. or, without the B<-q> flag, just
  473.  
  474.  :%!perltidy
  475.  
  476. It isn't necessary to format an entire file, however.  Perltidy will
  477. probably work well as long as you select blocks of text whose braces,
  478. parentheses, and square brackets are properly balanced.  You can
  479. even format an C<elsif> block without the leading C<if> block, as
  480. long as the text you select has all braces balanced.
  481.  
  482. For the B<emacs> editor, first mark a region and then pipe it through
  483. perltidy.  For example, to format an entire file, select it with C<C-x h> 
  484. and then pipe it with C<M-1 M-|> and then C<perltidy>.  The numeric
  485. argument, C<M-1> causes the output from perltidy to replace the marked
  486. text.  See "GNU Emacs Manual" for more information,
  487. http://www.gnu.org/manual/emacs-20.3/html_node/emacs_toc.html
  488.  
  489. If you have difficulty with an editor, try the B<-st> flag, which will
  490. force perltidy to send output to standard output.  This might be needed,
  491. for example, if the editor passes text to perltidy as temporary filename
  492. instead of through the standard input.  If this works, you might put the
  493. B<-st> flag in your F<.perltidyrc> file.
  494.  
  495. If you have some tips for making perltidy work with your editor, and
  496. are willing to share them, please email me (see below) and I'll try to
  497. incorporate them in this document or put up a link to them.
  498.  
  499. After you get your editor and perltidy successfully talking to each
  500. other, try formatting a snippet of code with a brace error to see what
  501. happens.  (Do not use the quiet flag, B<-q>, for this test).  Perltidy
  502. will send one line starting with C<##> to standard error output.  Your
  503. editor may either display it at the top of the reformatted text or at
  504. the bottom (or even midstream!).  You probably cannot control this, and
  505. perltidy can't, but you need to know where to look when an actual error
  506. is detected.
  507.  
  508. =head2 Writing an HTML File
  509.  
  510. Perltidy can switch between two different output modes.  We have been
  511. discussing what might be called its "beautifier" mode, but it can also
  512. output in HTML.  To do this, use the B<-html> flag, like this:
  513.  
  514.  perltidy -html testfile.pl
  515.  
  516. which will produce a file F<testfile.pl.html>.  There are many
  517. parameters available for adjusting the appearance of an HTML file, but a
  518. very easy way is to just write the HTML file with this simple command
  519. and then edit the stylesheet which is embedded at its top.
  520.  
  521. One important thing to know about the B<-html> flag is that perltidy can
  522. either send its output to its beautifier or to its HTML writer, but
  523. (unfortunately) not both in a single run.  So the situation can be
  524. represented like this:
  525.  
  526.                   ------------
  527.                   |          |     --->beautifier--> testfile.pl.tdy
  528.  testfile.pl -->  | perltidy | -->
  529.                   |          |     --->HTML -------> testfile.pl.html
  530.                   ------------
  531.  
  532. And in the future, there may be more output filters.  So if you would
  533. like to both beautify a script and write it to HTML, you need to do it
  534. in two steps.
  535.  
  536. =head2 Summary
  537.  
  538. That's enough to get started using perltidy.  
  539. When you are ready to create a F<.perltidyrc> file, you may find it
  540. helpful to use the F<stylekey> page as a guide at
  541. http://perltidy.sourceforge.net/stylekey.html
  542.  
  543. Many additional special
  544. features and capabilities can be found in the manual pages for perltidy
  545. at
  546. http://perltidy.sourceforge.net/perltidy.html
  547.  
  548. We hope that perltidy makes perl programming a little more fun.
  549. Please check the perltidy
  550. web site http://perltidy.sourceforge.net occasionally
  551. for updates.
  552.  
  553. The auther may be contacted at perltidy at users.sourceforge.net.
  554.  
  555. =cut
  556.