perltidy - a Perl script indenter and reformatter
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
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.
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.
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.
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.
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).
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.
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.
If you set the -npro flag, perltidy will not look for this file.
See also --tabs.
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.
Setting this flag is equivalent to setting --freeze-newlines and --freeze-whitespace.
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
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;
@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.
);
, };
,
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' );
if ($task) { yyy(); } # -icb else { zzz(); }
The default is not to do this, indicated by -nicb.
# this comment is indented (-ibc, default) if ($task) { yyy(); }
# this comment is not indented (-nibc) if ($task) { yyy(); }
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.
$i = 1 ; # -sts $i = 1; # -nsts (default)
for ( @a = @$ap, $u = shift @a ; @a ; $u = $v ) { # -sfs (default) for ( @a = @$ap, $u = shift @a; @a; $u = $v ) { # -nsfs
-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.
qw
quotesqw
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.
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.
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(); }
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)
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.
For example,
if ( $input_file eq '-' ) # -bli { important_function(); }
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.
This flag does not prevent perltidy from eliminating existing line breaks; see -freeze-newlines to completely prevent changes to line break points.
-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.
-lp -bl -noll -pt=2 -bt=2 -sbt=2 -icp
-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).
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.
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).
#!...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
.
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.
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.
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.
--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.
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.
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).
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.
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.
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.
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.
perl2web(1), perlstyle(1)
This man page documents perltidy version 20011020.
Steven L. Hancock email: perltidy at users.sourceforge.net http://perltidy.sourceforge.net
Copyright (c) 2000, 2001 by Steven L. Hancock
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.
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.