NAME

perltidy - a Perl script indenter and reformatter


SYNOPSIS

    perltidy [ options ] file1 file2 file3 ...
            (output goes to file1.tdy, file2.tdy, file3.tdy, ...)
    perltidy [ options ] file1 -o outfile
    perltidy [ options ] file1 -st >outfile
    perltidy [ options ] <infile >outfile


DESCRIPTION

Perltidy reads a Perl script and writes an indented, reformatted script. The default formatting tries to follow the recommendations in perlstyle(1).

Many users will find enough information in EXAMPLES to get started. New users may benefit from the short tutorial which comes with the distribution.

The formatting can be controlled in detail with numerous input parameters, which are described in OPTIONS.


EXAMPLES

  perltidy somefile.pl

This will produce a file somefile.pl.tdy containing the script reformatted using the default options, which approximate the style suggested in perlstyle(1). Perltidy never changes the input file.

  perltidy *.pl

Execute perltidy on all .pl files in the current directory with the default options. The output will be in files with an appended .tdy extension. For any file with an error, there will be a file with extension .ERR.

  perltidy -gnu somefile.pl

Execute perltidy on file somefile.pl with a style which approximates the GNU Coding Standards for C programs. The output will be somefile.pl.tdy.

  perltidy -i=3 somefile.pl

Execute perltidy on file somefile.pl, with 3 columns for each level of indentation (-i=3) instead of the default 4 columns. There will not be any tabs in the reformatted script, except for any which already exist in comments, pod documents, quotes, and here documents. Output will be somefile.pl.tdy.

  perltidy -i=3 -t somefile.pl

Same as the previous example, except that each set of 3 columns of indentation (-i=3) will be represented by one leading tab character (-t).

  perltidy -ce -l=72 somefile.pl

Execute perltidy on file somefile.pl with all defaults except use ``cuddled elses'' (-ce) and a maximum line length of 72 columns (-l=72) instead of the default 80 columns.

  perltidy -g somefile.pl

Execute perltidy on file somefile.pl and save a log file somefile.pl.LOG which shows the nesting of braces, parentheses, and square brackets at the start of every line.


OPTIONS

The entire command line is scanned for options, and they are processed before any files are processed. As a result, it does not matter whether flags are before or after any filenames. However, the relative order of parameters is important, with later parameters overriding the values of earlier parameters.

For each parameter, there is a long name and a short name. The short names are convenient for keyboard input, while the long names are self-documenting and therefore useful in scripts. It is customary to use two leading dashes for long names, but one may be used.

Most parameters which serve as on/off flags can be negated with a leading ``n'' (for the short name) or a leading ``no'' (for the long name). For example, the flag to use tabs is -t or --tabs. The flag to use no tabs (the default) is -nt or --notabs.

Options may not be bundled together. In other words, options -q and -g may NOT be entered as -qg.

Option names may be terminated early as long as they are uniquely identified. For example, instead of -dump-token-types, it would be sufficient to enter -dump-tok, or even -dump-t, to uniquely identify this command.

I/O control

-h, --help
Show summary of usage and exit.

-o=filename, --outfile=filename
Name of the output file (only if a single input file is being processed). If no output file is specified, and output is not redirected to the standard output, the output will go to filename.tdy.

-st, --standard-output
Perltidy must be able to operate on an arbitrarily large number of files in a single run, with each output being directed to a different output file. Obviously this would conflict with outputting to the single standard output device, so a special flag, -st, is required to request outputting to the standard output. For example,
  perltidy somefile.pl -st >somefile.new.pl

This option may only be used if there is just a single input file. When this option is used, perltidy will have to create a temporary copy of the output file, perltidy.TMPO, to feed to perl for syntax checking, unless allow syntax checking is disabled. This file will be deleted when the job finishes. The default is -nst or -nostandard-output.

-se, --standard-error-output
If perltidy detects an error when processing file somefile.pl, its default behavior is to write error messages to file somefile.pl.ERR. Use -se to cause all error meassages to be sent to the standard error output stream instead. This directive may be negated with -nse. Thus, you may place -se in a .perltidyrc and override it when desired with -nse on the command line.

-w, --warning-output
Setting -w causes perltidy to include any non-critical warning messages be reported as errors. These include messages about possible pod problems, possibly bad starting indentation level, and cautions about indirect object usage. The default, -nw or --nowarning-output, is not to include these warnings.

-q, --quiet
Deactivate error messages and syntax checking (for running under an editor).

For example, if you use a vi-style editor, such as vim, you may execute perltidy as a filter from within the editor using something like

 :n1,n2!perltidy -q

where n1,n2 represents the selected text. Without the -q flag, any error messages will mess up your screen. Besides, it is common to run perltidy on incomplete blocks from an editor, and you don't want to see any complaints about that. (Or maybe you do; in that case, be prepared to use your ``undo'' key).

-syn, --check-syntax
This causes perltidy to run perl -T -c to check syntax of input and output. The results are written to the .LOG file, which will be saved if an error is detected in the output script. The output script is not checked if the input script has a syntax error. To skip syntax checking, use -nsyn or --nocheck-syntax. Syntax checking is also deactivated by the --quiet flag, discussed above.

The default is to do a syntax check.

-log, --logfile
Save the .LOG file, which has many useful diagnostics. Perltidy always creates a .LOG file, but by default it is deleted unless a program bug is suspected. Setting the -log flag forces the log file to be saved.

-g=n, --logfile-gap=n
Set maximum interval between input code lines in the logfile. This purpose of this flag is to assist in debugging nesting errors. The value of n is optional. If you set the flag -g without the value of n, it will be taken to be 1, meaning that every line will be written to the log file. This can be helpful if you are looking for a brace, paren, or bracket nesting error.

Setting -g also causes the logfile to be saved, so it is not necessary to also include -log.

If no -g flag is given, a value of 50 will be used, meaning that at least every 50th line will be recorded in the logfile. This helps prevent excessively long log files.

Setting a negative value of n is the same as not setting -g at all.

-npro --noprofile
Ignore any .perltidyrc command file. Normally, perltidy looks first in your current directory for a .perltidyrc file of parameters. (The format is described below). If it finds one, it applies those options to the initial default values, and then it applies any that have been defined on the command line. If no .perltidyrc file is found, it looks for one in your home directory.

If you set the -npro flag, perltidy will not look for this file.

-opt, --show-options
Write a list of all options used to the .LOG file. This is useful for debugging command files. In the list, the status of on/off switches is indicated by a 0 for off and a 1 for on. Please see --dump-options for a simpler way to do this.

-f, --force-read-binary
Force perltidy to process binary files. Normally, perltidy skips files identified by the system as non-text. This flag causes all existing files to be processed.

Basic Options

-i=n, --indent-columns=n
Use n columns per indentation level (default n=4).

See also --tabs.

-t, --tabs
This flag defines the characters used to indicate the indentation level of each line of code to be tabs. Perltidy allows two possible ways to represent the indentation at the beginning of each line of code. You may either use one tab character per level of indentation (signified with the -t flag), or you may use n real space characters per level, (where n is defined by the -i flag). The choice depends upon which is most convenient for your editor or viewer. The default is to use ASCII space characters because they should be properly displayed on all editors or viewers, even though they are not always the most convenient for editing. Of course, you can always rerun perltidy to change the indentation characters.

If you choose tabs, you will want to give the appropriate setting to your editor to display tabs as 4 blanks (or whatever value has been set with the -i command).

Except for these possible tab indentation characters, Perltidy does not introduce any tab characters into your file, and it removes any tabs from the code (unless requested not to do so with -fws). If you have any tabs in your comments, quotes, or here-documents, they will remain.

-nt, --notabs
Use space (blank) characters instead of tabs for leading indentation. This is the default, following the recommendation in perlstyle(1), although some programmers will prefer tabs.

-io, --indent-only
This flag is used to deactivate all formatting and line break changes. When it is in effect, the only change to the script will be indentation. And any flags controlling whitespace and newlines will be ignored. You might want to use this if you are perfectly happy with your whitespace and line breaks, and merely want perltidy to handle the indentation. (This also speeds up perltidy by about a factor of two, so it might be useful when perltidy is merely being used to help find a brace error in a large script).

Setting this flag is equivalent to setting --freeze-newlines and --freeze-whitespace.

Whitespace Control

-fws, --freeze-whitespace
This flag causes your original whitespace to remain unchanged, and causes the rest of the whitespace commands in this section to be ignored.

Tightness of curly braces, parentheses, and square brackets.
Here the term ``tightness'' will mean the closeness with which pairs of enclosing tokens, such as parentheses, contain the quantities within. A numerical value of 0, 1, or 2 defines the tightness, with 0 being least tight and 2 being most tight.

The -pt=n or --paren-tightness parameter controls the space within parens. The example below shows the effect of the three possible values, 0, 1, and 2:

 if ( ( my $len_tab = length( $tabstr ) ) > 0 ) {  # -pt=0
 if ( ( my $len_tab = length($tabstr) ) > 0 ) {    # -pt=1 (default)
 if ((my $len_tab = length($tabstr)) > 0) {        # -pt=2

When n is 0, there is always a space to the right of a '(' and to the left of a ')'. For n=2 there is never a space. For n=1, the default, there is a space unless the quantity within the parens is a single token, such as an identifier or quoted string.

Likewise, the parameter -sbt=n or --square-bracket-tightness controls the space within square brackets, as illustrated below.

 $width = $col[ $j + $k ] - $col[ $j ];  # -sbt=0
 $width = $col[ $j + $k ] - $col[$j];    # -sbt=1 (default)
 $width = $col[$j + $k] - $col[$j];      # -sbt=2

Curly braces which do not contain code blocks are controlled by the parameter -bt=n or --brace-tightness=n.

 $obj->{ $parsed_sql->{ 'table' }[0] };    # -bt=0
 $obj->{ $parsed_sql->{'table'}[0] };      # -bt=1 (default)
 $obj->{$parsed_sql->{'table'}[0]};        # -bt=2

And finally, curly braces which contain blocks of code are controlled by the parameter -bbt=n or --block-brace-tightness=n as illustrated in the example below.

 %bf = map { $_ => -M $_ } grep { /\.deb$/ } dirents '.'; # -bbt=0 (default)
 %bf = map { $_ => -M $_ } grep {/\.deb$/} dirents '.';   # -bbt=1
 %bf = map {$_ => -M $_} grep {/\.deb$/} dirents '.';     # -bbt=2

-ci=n, --continuation-indentation=n
Continuation indentation is extra indentation spaces applied when a long line is broken. The default is n=2, illustrated here:
 my $level =   # -ci=2      
   ( $max_index_to_go >= 0 ) ? $levels_to_go[0] : $last_output_level;

The same example, with n=0, is a little harder to read:

 my $level =   # -ci=0    
 ( $max_index_to_go >= 0 ) ? $levels_to_go[0] : $last_output_level;

List indentation using -lp, --line-up-parentheses
By default, perltidy indents lists with 4 spaces, or whatever value is specified with -i=n. Here is a small list formatted in this way:
    @month_of_year = (
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
        'Nov', 'Dec'
    );

Use the -lp flag to add extra indentation to cause the data to begin past the opening parentheses of a sub call or list, or opening square bracket of an anonymous array, or opening curly brace of an anonymous hash. With this option set, the above list would become:

    @month_of_year = (
                       'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
                       'Sep', 'Oct', 'Nov', 'Dec'
    );

If the available line length (see -l=n ) does not permit this much space, perltidy will use less.

This option has no effect on code BLOCKS, such as if/then/else blocks, which always use whatever is specified with -i=n. Also, the existance of line breaks and/or block comments between the opening and closing parens may cause perltidy to temporarily revert to its default method.

Note: The -lp option may not be used together with the -t tabs option. If -t is specified, it will be ignored.

In addition, any parameter which restricts the ability of perltidy to choose newlines will all conflict with -lp and will cause -lp to be deactivated. These include -io, -fnl, -nanl, and -ndnl.

-icp, --indent-closing-paren
The -icp option leaves a list-termination line of the form );, };, or ]; indented with the same indentation as the previous line. The previous example with -icp would give,
    @month_of_year = (          # -icp
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
        'Nov', 'Dec'
        );

-icb, --indent-closing-brace
The -icb option leaves a brace which terminates a code block indented with the same indentation as the previous line. For example,
        if ($task) {
            yyy();
            }    # -icb
        else {
            zzz();
            }

The default is not to do this, indicated by -nicb.

-ibc, --indent-block-comments
Block comments, meaning full-line comments, normally look best when they are indented to the same level as the code which follows them. This is the default behavior, but you may use -nibc to keep block comments left-justified. Here is an example:
             # this comment is indented      (-ibc, default)
             if ($task) { yyy(); }

-nibc, --noindent-block-comments
Do not indent block comments. Here is an example:
 # this comment is not indented              (-nibc)
             if ($task) { yyy(); }

-hsc, --hanging-side-comments
By default, perltidy tries to identify and align ``hanging side comments'', which are something like this:
        my $IGNORE = 0;    # This is a side comment
                           # This is a hanging side comment
                           # And so is this

A comment is considered to be a hanging side comment if it immediately follows a line with a side comment, or another hanging side comment. To deactivate this feature, use -nhsc or --nohanging-side-comments. If block comments are preceded by a blank line, they will not be mistaken as hanging side comments.

-oll, --outdent-long-lines
When -oll is set, lines which cannot be broken into pieces less than the maximum-line-length will have their indentation removed to make them more readable. This is the default. This can mainly occur for long quoted strings and long comments. To prevent such out-denting, use -noll or --nooutdent-long-lines.

-msc=n, minimum-space-to-comment=n
Side comments look best when lined up several spaces to the right of code. Perltidy will try to keep comments at least n spaces to the right. The default is n=4 spaces.

-sts, --space-terminal-semicolon
Some programmers prefer a space before all terminal semicolons. The default is for no such space, and is indicated with -nsts or --nospace-terminal-semicolon.
        $i = 1 ;     #  -sts
        $i = 1;      #  -nsts   (default)

-sfs, --space-for-semicolon
Semicolons within for loops may sometimes be hard to see, particularly when commas are also present. This option places spaces on both sides of these special semicolons, and is the default. Use -nsfs or --nospace-for-semicolon to deactivate it.
 for ( @a = @$ap, $u = shift @a ; @a ; $u = $v ) {  # -sfs (default)
 for ( @a = @$ap, $u = shift @a; @a; $u = $v ) {    # -nsfs

-asc, --add-semicolons
Setting -asc allows perltidy to add any missing optional semicolon at the end of a line which is followed by a closing curly brace on the next line. This is the default, and may be deactivated with -nasc or --noadd-semicolons.

-dsm, --delete-semicolons
Setting -dsm allows perltidy to delete extra semicolons which are simply empty statements. This is the default, and may be deactivated with -ndsm or --nodelete-semicolons. (Such semicolons are not deleted, however, if they would promote a side comment to a block comment).

-aws, --add-whitespace
Setting this option allows perltidy to add certain whitespace improve code readability. This is the default. If you do not want any whitespace added, but are willing to have some whitespace deleted, use -naws. (Use -fws to leave whitespace completely unchanged).

-dws, --delete-old-whitespace
Setting this option allows perltidy to remove some old whitespace between characters, if necessary. This is the default. If you do not want any old whitespace removed, use -ndws or --nodelete-old-whitespace.

Detailed whitespace controls
For those who want more detailed control over the whitespace around tokens, there are four parameters which can directly modify the default whitespace rules built into perltidy for any token. They are:

-wls=s or --want-left-space=s,

-nwls=s or --nowant-left-space=s,

-wrs=s or --want-right-space=s,

-nwrs=s or --nowant-right-space=s.

These parameters are each followed by a quoted string, s, containing a list of token types. No more than one of each of these parameters should be specified, because repeating a command-line parameter always overwrites the previous one before perltidy ever sees it.

To illustrate how these are used, suppose it is desired that there be no space on either side of the token types = + - / *. The following two parameters would specify this desire:

  -nwls="= + - / *"    -nwrs="= + - / *"

(Note that the token types are in quotes, and that they are separated by spaces). With these modified whitespace rules, the following line of math:

  $root = -$b + sqrt( $b * $b - 4. * $a * $c ) / ( 2. * $a );

becomes this:

  $root=-$b+sqrt( $b*$b-4.*$a*$c )/( 2.*$a );

These parameters should be considered to be hints to perltidy rather than fixed rules, because perltidy must try to resolve conflicts that arise between them and all of the other rules that it uses. One conflict that can arise is if, between two tokens, the left token wants a space and the right one doesn't. In this case, the token not wanting a space takes priority.

It is necessary to have a list of all token types in order to create this type of input. Such a list can be obtained by the command -dump-token-types.

Trimming whitespace around qw quotes
-tqw or --trim-qw provide the default behavior of trimming spaces around multiline qw quotes and indenting them appropriately.

-ntqw or --notrim-qw cause leading and trailing whitespace around multi-line qw quotes to be left unchanged. This option will not normally be necessary, but was added for testing purposes, because in some versions of perl, trimming qw quotes changes the syntax tree.

Line Break Control

-fnl, --freeze-newlines
If you do not want any changes to the line breaks in your script, set -fnl, and they will remain fixed, and the rest of the commands in this section will be ignored. You may want to use -noll with this.

-l=n, --maximum-line-length=n
The default maximum line length is n=80 characters. Perltidy will try to find line break points to keep lines below this length. However, long quotes and side comments may cause lines to exceed this length. Setting -l=0 is equivalent to setting -l=(a large number).

-bbc, --blanks-before-comments
A blank line will be introduced before a full-line comment. This is the default. Use -nbbc or --noblanks-before-comments to prevent such blank lines from being introduced.

-bbs, --blanks-before-subs
A blank line will be introduced before a sub definition, unless it is a one-liner or preceded by a comment. A blank line will also be introduced before a package statement and a BEGIN and END block. This is the default. The intention is to help display the structure of a program by setting off certain key sections of code. This is negated with -nbbs or --noblanks-before-subs.

-bbb, --blanks-before-blocks
A blank line will be introduced before blocks of coding delimited by for, foreach, while, until, and if, unless, in the following circumstances:

This is the default. The intention of this option is to introduce some space within dense coding. This is negated with -nbbb or --noblanks-before-blocks.

-lbl=n --long-block-line-count=n
This controls how often perltidy is allowed to add blank lines before certain block types (see previous section). The default is 8. Entering a value of 0 is equivalent to entering a very large number.

-mbl=n --maximum-consecutive-blank-lines=n
This parameter specifies the maximum number of consecutive blank lines in the output script. The default is n=1. If the input file has more than n consecutive blank lines, the number will be reduced to n.

-sob, --swallow-optional-blank-lines
Blank lines governed by the above flags, -bbb, -bbs, and -bbc, will be deleted. (But essential blank lines above pod documents will be retained). This is NOT the default.

-nsob, --noswallow-optional-blank-lines
Retain blank lines, including those which do not corresponding to flags -bbb, -bbs, and -bbc. This is the default. The number of blanks retained is subject to the limit imposed by --maximum-consecutive-blank-lines, however.

-ce, --cuddled-else
Enable the ``cuddled else'' style, in which else and elsif are follow immediately after the curly brace closing the previous block. The default is not to use cuddled elses, and is indicated with the flag -nce or --nocuddled-else. Here is a comparison of the alternatives:
  if ($task) {
      yyy();
  } else {    # -ce
      zzz();
  }
  if ($task) {
        yyy();
  }
  else {    # -nce  (default)
        zzz();
  }

-bl, --opening-brace-on-new-line
Use the flag -bl to place the opening brace on a new line:
  if ( $input_file eq '-' )    # -bl 
  {                          
      important_function();
  }

This flag applies to all structural blocks, including sub's (unless the -sbl flag is set -- see next item).

The default style, -nbl, places an opening brace on the same line as the keyword introducing it. For example,

  if ( $input_file eq '-' ) {   # -nbl (default)

-sbl, --opening-sub-brace-on-new-line
The flag -sbl can be used to override the value of -bl for opening sub braces. For example,
 perltidy -sbl

produces this result:

 sub foo
 {
    if (!defined($_[0])) {
        print("Hello, World\n");
    }
    else {
        print($_[0], "\n");
    }
 }

This flag is negated with -nsbl. If -sbl is not specified, the value of -bl is used.

-bli, --brace-left-and-indent
The flag -bli is the same as -bl but in addition it causes one unit of continuation indentation ( see -ci ) to be placed before an opening and closing brace associated with the keywords if, elsif, else, unless, for, foreach, sub, while, until, and also with a preceding label.

For example,

        if ( $input_file eq '-' )    # -bli
          {
            important_function();
          }

-bar, --opening-brace-always-on-right
The default style, -nbl places the opening brace on a new line if it does not fit on the same line as the opening keyword, like this:
        if ( $bigwasteofspace1 && $bigwasteofspace2
          || $bigwasteofspace3 && $bigwasteofspace4 )
        {
            big_waste_of_time();
        }

To force the opening brace to always be on the right, use the -bar flag. In this case, the above example becomes

        if ( $bigwasteofspace1 && $bigwasteofspace2
          || $bigwasteofspace3 && $bigwasteofspace4 ) {
            big_waste_of_time();
        }

A conflict occurs if both -bl and -bar are specified.

-dnl, --delete-old-newlines
By default, perltidy first deletes all old line break locations, and then it looks for optimal break points to match the desired line length. Use -ndnl or --nodelete-old-newlines to force perltidy to retain all old line break points.

-anl, --add-newlines
By default, perltidy will add line breaks when necessary to create continuations of long lines and to improve the script appearance. Use -nanl or -noadd-newlines to prevent any new line breaks.

This flag does not prevent perltidy from eliminating existing line breaks; see -freeze-newlines to completely prevent changes to line break points.

Controlling whether perltidy breaks before or after operators
Two command line parameters provide some control over whether a line break should be before or after specific token types.

-wba=s or --want-break-after=s, and

-wbb=s or --want-break-before=s.

These parameters are each followed by a quoted string, s, containing a list of token types (separated only by spaces). No more than one of each of these parameters should be specified, because repeating a command-line parameter always overwrites the previous one before perltidy ever sees it.

By default, perltidy breaks after these token types: % + - * / x != == >= <= =~ !~ < > | & >= < = **= += *= &= <<= &&= -= /= |= >>= ||= .= %= ^= x=

And perltidy breaks before these token types by default: . << >> -> && ||

To illustrate, to cause a break after a concatenation operator, '.', rather than before it, the command line would be

  -wba="."

As another example, the following command would cause a break before math operators '+', '-', '/', and '*':

  -wbb="+ - / *"

These commands should work well for most of the token types that perltidy uses (use --dump-token-types for a list). However, for a few token types there may be conflicts with hardwired logic which cause unexpected results. An example is the comma, which is hardwired to go at the end of lines in certain cases. Hopefully, this restriction will be removed in the future. Another example is curly braces, which should be controlled with the parameter bl provided for that purpose.

Styles

-gnu, --gnu-style
-gnu gives an approximation to the GNU Coding Standards (which do not apply to perl) as they are sometimes implemented. At present, this style overrides the default style with the following parameters:
    -lp -bl -noll -pt=2 -bt=2 -sbt=2 -icp

Other Controls

Writing selected text to a file
When perltidy writes a formatted text file, it has the ability to also send selected text to a file with a .TEE extension. This text can include comments and pod documentation. The relevant commands are: -tac or --tee-all-comments, -tbc or --tee-block-comments, -tsc or --tee-side-comments, and -tp or --tee-pod. The negatives of these commands also work, and are the defaults.

Deleting selected text
Perltidy can selectively delete comments and pod documentation. The commands to do this are:

-dac or --delete-all-comments, -dbc or --delete-block-comments, -dsc or --delete-side-comments, and -dp or --delete-pod. The negatives of these commands also work, and are the defaults. When block comments are deleted, any leading 'hash-bang' will be retained. Also, if the -x flag is used, any system commands before a leading hash-bang will be retained (even if they are in the form of comments).

Using a .perltidyrc command file
If you use perltidy frequently, you probably won't be happy until you create a .perltidyrc file to avoid typing commonly-used parameters. Perltidy will first look in your current directory for a command file named .perltidyrc, and if it does not find one, it will look in your home directory. If it does not find one there, it will look for a system-wide file /usr/local/etc/perltidyrc, and failing to find one there it will look for /etc/perltidyrc. Note that the system-wide files do not have a leading dot.

This file is free format, and simply a list of parameters, just as they would be entered on a command line. Any number of lines may be used, with any number of parameters per line, although it may be easiest to read with one parameter per line. Blank lines are ignored, and text after a '#' is ignored to the end of a line.

Here is an example of a .perltidyrc file:

  # This is a simple of a .perltidyrc configuration file
  # This implements a highly spaced style
  -se    # errors to standard error output
  -w     # show all warnings
  -bl    # braces on new lines
  -pt=0  # parens not tight at all
  -bt=0  # braces not tight
  -sbt=0 # square brackets not tight

The parameters in the .perltidyrc file are installed first, so any parameters given on the command line will have priority over them.

To avoid confusion, perltidy ignores any command in the .perltidyrc file which would cause some kind of dump and an exit. These are:

 -h -v -ddf -dln -dop -dsn -dtt -dwls -dwrs -ss

There are several options may be helpful in debugging a .perltidyrc file. First, -log will force a .LOG file to be written, which contains the path to the .perltidyrc file, if any, and a listing of its parameter settings. Second, -opt will force a .LOG file to be written with a complete listing of all option flags in use for a run, taking into account the default settings, the .perltidyrc file, plus any command line options. Third, the parameters in the .perltidyrc file can be ignored with the -npro option. Finally, the commands -dump-options, -dump-defaults, -dump-long-names, and -dump-short-names, all described below, may all be helpful.

Creating a new abbreviation
A special notation is available for use in a .perltidyrc file for creating an abbreviation for a group of options. This can be used to create a shorthand for one or more styles which are frequently, but not always, used. The notation is to group the options within curly braces which are preceded by the name of the alias (without leading dashes), like this:
        newword {
        -opt1
        -opt2
        }

where newword is the abbreviation, and opt1, etc, are existing parameters or other abbreviations. The main syntax requirement is that the new abbreviation must begin on a new line. Space before and after the curly braces is optional. For a specific example, the following line

        airy {-bl -pt=0 -bt=0 -sbt=0}

could be placed in a .perltidyrc file, and then invoked at will with

        perltidy -airy somefile.pl

(Either -airy or --airy may be used).

-sil=n --starting-indentation-level=n
By default, perltidy examines the input file and tries to determine the starting indentation level. While it is often zero, it may not be zero for a code snippet being sent from an editing session. If the default method does not work correctly, or you want to change the starting level, use -sil=n, to force the starting level to be n.

Skipping leading non-perl commands with -x or --look-for-hash-bang
If your script has leading lines of system commands or other text which are not valid perl code, and which are separated from the start of the perl code by a ``hash-bang'' line, ( a line of the form #!...perl ), you must use the -x flag to tell perltidy not to parse and format any lines before the ``hash-bang'' line. This option also invokes perl with a -x flag when checking the syntax. This option was originally added to allow perltidy to parse interactive VMS scripts, but it should be used for any script which is normally invoked with perl -x.

Controlling list formatting and vertical alignment
Perltidy attempts to place comma-separated arrays of values in tables which can be vertically aligned. The number of fields is, by default, chosen to be the largest even number which fits in the current page width (defined by -l=n). Usually this works well.

There are two ways to control this formatting. The first is with the use of comments or empty lines. If there are any comments or blank lines between the opening and closing structural brace, parenthesis, or bracket containing the list, then the original line breaks will be used for the entire list instead.

The second is with the parameter --mft=n or --maximum-fields-per-table=n. The default value for n is a large number, 40. If the computed number of fields for any table exceeds n, then it will be reduced to n. While this value should probably be left unchanged as a general rule, it might be used on a small section of code to force a list to have a particular number of fields per line, and then a single comment could be introduced somewhere to freeze the formatting in future applications of perltidy, like this:

    @month_of_year = (    # -mft=2
        'Jan', 'Feb',
        'Mar', 'Apr',
        'May', 'Jun',
        'Jul', 'Aug',
        'Sep', 'Oct',
        'Nov', 'Dec'
    );

Vertical alignment refers to lining up similar tokens vertically, like this:

 my $lines     = 0;    # checksum: #lines
 my $bytes     = 0;    # checksum: #bytes
 my $sum       = 0;    # checksum: system V sum

Once the perltidy vertical aligner ``locks on'' to a pattern, such as defined by the ``='' and ``#'' in the above example, it retains the pattern for as long as possible. However, a blank line or full-line comment will cause it to forget the pattern and start looking for another. Thus, a single blank line can be introduced to force the aligner to stop aligning when it is undesirable.

Making a file unreadable
The goal of perltidy is to improve the readability of files, but there are two commands which have the opposite effect, --mangle and --extrude. They are actually merely aliases for combinations of other parameters. Both of these strip all possible whitespace, but leave comments and pod documents, so that they are essentially reversible. The difference between these is that --mangle puts the fewest possible line breaks in a script while --extrude puts the maximum possible. Note that these options do not provided any meaningful obfuscation, because perltidy can be used to reformat the files. A useful application of --mangle is the following:
  perltidy -mangle myfile.pl -st | perltidy -o myfile.pl.new

This will form the maximum possible number of one-line blocks (see next section), and can sometimes help clean up a badly formatted script.

One-line blocks
There are a few points to note regarding one-line blocks. A one-line block is something like this,
        if ($x > 0) { $y = 1 / $x }

where the contents within the curly braces is short enough to fit on a single line.

With few exceptions, Perltidy retains existing one-line blocks, if it is possible within the line-length constraint, but it does not attempt to form new ones. In other words, Perltidy will try to follow the one-line block style of the input file.

If an existing one-line block is longer than the maximum line length, however, it will be broken into multiple lines. When this happens, perltidy checks for and adds any optional terminating semicolon (unless the -nasc option is used) if the block is a code block.

The main exception is that Perltidy will attempt to form new one-line blocks following the keywords map, eval, and sort, because these code blocks are often small and most clearly displayed in a single line.

Occasionally it is helpful to introduce line breaks in lists containing a '=>' symbol, which is sometimes called a ``comma-arrow''. To force perltidy to introduce breaks in a one-line block containing comma arrows, use the --break-after-comma-arrows, or -baa, flag. For example, given the following single line, Perltidy will not add any line breaks:

    bless { B => $B, Root => $Root } => $package;   -nbaa (default)

To introduce breaks to show the structure, use -baa:

    bless {                                         -baa
        B    => $B,
        Root => $Root
    } => $package;

One-line block rules can conflict with the cuddled-else option. When the cuddled-else option is used, perltidy retains existing one-line blocks, even if they do not obey cuddled-else formatting.

Occasionally, when one-line blocks get broken because they exceed the available line length, the formatting will violate the requested brace style. If this happens, reformatting the script a second time should correct the problem.

Debugging
The following flags are available for debugging:

--dump-defaults or -ddf will write the default option set to standard output and quit

--dump-options or -dop will write current option set to standard output and quit.

--dump-long-names or -dln will write all command line long names (passed to Get_options) to standard output and quit.

--dump-short-names or -dsn will write all command line short names to standard output and quit.

--dump-token-types or -dtt will write a list of all token types to standard output and quit.

--dump-want-left-space or -dwls will write the hash %want_left_space to standard output and quit. See the section on controlling whitespace around tokens.

--dump-want-right-space or -dwrs will write the hash %want_right_space to standard output and quit. See the section on controlling whitespace around tokens.

-DEBUG will write a file with extension .DEBUG for each input file showing the tokenization of all lines of code.

Working with MakeMaker, AutoLoader and SelfLoader
The first $VERSION line of a file which might be eval'd by MakeMaker is passed through unchanged except for indentation. Use --nopass-version-line, or -npvl, to deactivate this feature.

If the AutoLoader module is used, perltidy will continue formatting code after seeing an __END__ line. Use --nolook-for-autoloader, or -nlal, to deactivate this feature.

Likewise, if the SelfLoader module is used, perltidy will continue formatting code after seeing a __DATA__ line. Use --nolook-for-selfloader, or -nlsl, to deactivate this feature.

Writing an HTML file
The flag -html causes perltidy to write an html file with extension .html. So, for example, the following command
        perltidy -html somefile.pl

will produce a syntax-colored html file named somefile.pl.html which may be viewed with a browser.

Documentation for this option has been moved to a separate man page, perl2web(1).


SWITCHES WHICH MAY BE NEGATED

The following list shows all short parameter names which allow a prefix 'n' to produce the negated form:

    D anl asc aws bbb bbc bbs bli baa syn ce dac dbc dnl
    dws dp dsm dsc ddf dln dop dsn dtt dwls dwrs f fll
    hsc html ibc icb icp lp log lal x lsl bl sbl oll pvl
    q opt sfs sts se st sob t tac tbc tp tsc tqw w

Equivalently, the prefix 'no' on the corresponding long names may be used.


LIMITATIONS

Parsing Limitations
Perltidy should work properly on most Perl scripts. It does a lot of self-checking, but still, it is possible that an error could be introduced and go undetected. Therefore, it is essential to make careful backups and to test reformatted scripts.

The main current limitation is that perltidy does not scan modules included with 'use' statements. This makes it necessary to guess the context of any bare words introduced by such modules. Perltidy has good guessing algorithms, but they are not infallible. When it must guess, it leaves a message in the log file.

If you encounter a bug, please report it.

What perltidy does not parse and format
Perltidy indents but does not reformat comments and qw quotes. Perltidy does not in any way modify the contents of here documents or quoted text, even if they contain source code. (You could, however, reformat them separately). Perltidy does not format 'format' sections in any way. And, of course, it does not modify pod documents.


FILES

Special files when standard input or standard output are used
When standard input is used, the log file, if saved, is perltidy.LOG, and any errors are written to perltidy.ERR unless the -se flag is set. These are saved in the current working directory. If syntax checking is used, a temporary copy of the input file will be created in the current working directory called perltidy.TMPI, but it will be removed when perltidy finishes.

When standard output and syntax checking are used, a temporary copy of the output file will be created in the current working directory called perltidy.TMPO. It will be removed when perltidy finishes.

Files overwritten
The following file extensions are used by perltidy, and files with these extensions may be overwritten or deleted: .tdy, .ERR, .LOG, .TEE, .TMPI, .TMPO.

Files extensions limitations
Perltidy does not operate on files for which the run could produce a file with a duplicated file extension. These extensions are .tdy, .LOG, .ERR, .TEE, .TMPI, .TMPO. The purpose of this rule is to prevent generating confusing filenames such as somefile.tdy.tdy.tdy.


SEE ALSO

perl2web(1), perlstyle(1)


VERSION

This man page documents perltidy version 20011020.


AUTHOR

  Steven L. Hancock
  email: perltidy at users.sourceforge.net
  http://perltidy.sourceforge.net


COPYRIGHT

Copyright (c) 2000, 2001 by Steven L. Hancock


LICENSE

This package is free software; you can redistribute it and/or modify it under the terms of the ``GNU General Public License''.

Please refer to the file ``COPYING'' for details.


DISCLAIMER

This package is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the ``GNU General Public License'' for more details.