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).
The short EXAMPLES section may contain enough information to get many users 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 the OPTIONS section.
perltidy somefile.pl
This will produce a file somefile.pl.tdy containing the script reformatted using the default options.
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 files with extensions .ERR and .LOG.
perltidy -i=3 somefile.pl
Execute perltidy on file somefile.pl, with 3 columns for each level of indentation (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 will be represented by one leading tab character.
perltidy -ce -l=72 somefile.pl
Execute perltidy on file somefile.pl with all defaults except use ``cuddled elses'' and a maximum line length of 72 columns (instead of the default 80 columns).
perltidy -io somefile.pl
Execute perltidy on file somefile.pl but restrict changes to ``indentation only'', which means that existing line breaks and whitespace will be unchanged.
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 them 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 a single input file.
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 -c
to check syntax of input and output.
This is the default and highly recommended. 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.
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 -bt=n or --brace-tightness=n controls the space within curly braces, as illustrated in the example below.
if ( $Opts{ help } ) { usage(); exit 1; } # -bt=0 if ( $Opts{help} ) { usage(); exit 1; } # -bt=1 (default) if ( $Opts{help} ) {usage(); exit 1;} # -bt=2
And finally, 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
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;
# this comment is indented (-ibc, default) if ($task) { yyy(); }
# this comment is not indented (-nibc) if ($task) { yyy(); }
$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 specifying a second parameter always overwrites the previous one.
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.
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
This flag applies to all structural blocks, including sub's.
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)
This flag does not prevent perltidy from eliminating existing line breaks; see -freeze-newlines to completely prevent changes to line break points.
-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.
Here is an example of a .perltidyrc file:
# This is a simple of a .perltidyrc configuration file # This implements a highly spaced style -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.
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.
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.
-dump-defaults will write the default option set to standard output and quit
-dump-options will write current option set to standard output and quit.
-dump-long-names will write all command line long names (passed to Get_options) to standard output and quit.
-dump-short-names will write all command line short names to standard output and quit.
-dump-token-types will write a list of all token types to standard output and quit.
-dump-want-left-space will write the hash %want_left_space to standard output and quit. See the section on controlling whitespace around tokens.
-dump-want-right-space 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.
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 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 20010406.
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.