6 my $arg_string = undef;
8 # give Macs a chance to provide command line parameters
10 $arg_string = MacPerl::Ask(
11 'Please enter @ARGV (-h for help)',
12 defined $ARGV[0] ? "\"$ARGV[0]\"" : ""
16 # Exit codes returned by perltidy:
18 # 1 = perltidy could not run to completion due to errors
19 # 2 = perltidy ran to completion with error messages
20 exit Perl::Tidy::perltidy( argv => $arg_string );
26 perltidy - a perl script indenter and reformatter
30 perltidy [ options ] file1 file2 file3 ...
31 (output goes to file1.tdy, file2.tdy, file3.tdy, ...)
32 perltidy [ options ] file1 -o outfile
33 perltidy [ options ] file1 -st >outfile
34 perltidy [ options ] <infile >outfile
38 Perltidy reads a perl script and writes an indented, reformatted script.
39 This document describes the parameters available for controlling this formatting.
41 Perltidy is a commandline frontend to the module Perl::Tidy. For documentation
42 describing how to call the Perl::Tidy module from other applications see the
43 separate documentation for Perl::Tidy. It is the file Perl::Tidy.pod in the source distribution.
45 Many users will find enough information in L<"EXAMPLES"> to get
46 started. New users may benefit from the short tutorial
48 http://perltidy.sourceforge.net/tutorial.html
50 A convenient aid to systematically defining a set of style parameters
52 http://perltidy.sourceforge.net/stylekey.html
54 Perltidy can produce output on either of two modes, depending on the
55 existence of an B<-html> flag. Without this flag, the output is passed
56 through a formatter. The default formatting tries to follow the
57 recommendations in perlstyle(1), but it can be controlled in detail with
58 numerous input parameters, which are described in L<"FORMATTING OPTIONS">.
60 When the B<-html> flag is given, the output is passed through an HTML
61 formatter which is described in L<"HTML OPTIONS">.
67 This will produce a file F<somefile.pl.tdy> containing the script reformatted
68 using the default options, which approximate the style suggested in
69 perlstyle(1). The source file F<somefile.pl> is unchanged.
73 Execute perltidy on all F<.pl> files in the current directory with the
74 default options. The output will be in files with an appended F<.tdy>
75 extension. For any file with an error, there will be a file with extension
78 perltidy -b file1.pl file2.pl
80 Modify F<file1.pl> and F<file2.pl> in place, and backup the originals to
81 F<file1.pl.bak> and F<file2.pl.bak>. If F<file1.pl.bak> and/or F<file2.pl.bak>
82 already exist, they will be overwritten.
84 perltidy -b -bext='/' file1.pl file2.pl
86 Same as the previous example except that the backup files F<file1.pl.bak> and F<file2.pl.bak> will be deleted if there are no errors.
88 perltidy -gnu somefile.pl
90 Execute perltidy on file F<somefile.pl> with a style which approximates the
91 GNU Coding Standards for C programs. The output will be F<somefile.pl.tdy>.
93 perltidy -i=3 somefile.pl
95 Execute perltidy on file F<somefile.pl>, with 3 columns for each level of
96 indentation (B<-i=3>) instead of the default 4 columns. There will not be any
97 tabs in the reformatted script, except for any which already exist in comments,
98 pod documents, quotes, and here documents. Output will be F<somefile.pl.tdy>.
100 perltidy -i=3 -et=8 somefile.pl
102 Same as the previous example, except that leading whitespace will
103 be entabbed with one tab character per 8 spaces.
105 perltidy -ce -l=72 somefile.pl
107 Execute perltidy on file F<somefile.pl> with all defaults except use "cuddled
108 elses" (B<-ce>) and a maximum line length of 72 columns (B<-l=72>) instead of
109 the default 80 columns.
111 perltidy -g somefile.pl
113 Execute perltidy on file F<somefile.pl> and save a log file F<somefile.pl.LOG>
114 which shows the nesting of braces, parentheses, and square brackets at
115 the start of every line.
117 perltidy -html somefile.pl
119 This will produce a file F<somefile.pl.html> containing the script with
120 html markup. The output file will contain an embedded style sheet in
121 the <HEAD> section which may be edited to change the appearance.
123 perltidy -html -css=mystyle.css somefile.pl
125 This will produce a file F<somefile.pl.html> containing the script with
126 html markup. This output file will contain a link to a separate style
127 sheet file F<mystyle.css>. If the file F<mystyle.css> does not exist,
128 it will be created. If it exists, it will not be overwritten.
130 perltidy -html -pre somefile.pl
132 Write an html snippet with only the PRE section to F<somefile.pl.html>.
133 This is useful when code snippets are being formatted for inclusion in a
134 larger web page. No style sheet will be written in this case.
136 perltidy -html -ss >mystyle.css
138 Write a style sheet to F<mystyle.css> and exit.
140 perltidy -html -frm mymodule.pm
142 Write html with a frame holding a table of contents and the source code. The
143 output files will be F<mymodule.pm.html> (the frame), F<mymodule.pm.toc.html>
144 (the table of contents), and F<mymodule.pm.src.html> (the source code).
146 =head1 OPTIONS - OVERVIEW
148 The entire command line is scanned for options, and they are processed
149 before any files are processed. As a result, it does not matter
150 whether flags are before or after any filenames. However, the relative
151 order of parameters is important, with later parameters overriding the
152 values of earlier parameters.
154 For each parameter, there is a long name and a short name. The short
155 names are convenient for keyboard input, while the long names are
156 self-documenting and therefore useful in scripts. It is customary to
157 use two leading dashes for long names, but one may be used.
159 Most parameters which serve as on/off flags can be negated with a
160 leading "n" (for the short name) or a leading "no" or "no-" (for the
161 long name). For example, the flag to outdent long quotes is B<-olq>
162 or B<--outdent-long-quotes>. The flag to skip this is B<-nolq>
163 or B<--nooutdent-long-quotes> or B<--no-outdent-long-quotes>.
165 Options may not be bundled together. In other words, options B<-q> and
166 B<-g> may NOT be entered as B<-qg>.
168 Option names may be terminated early as long as they are uniquely identified.
169 For example, instead of B<--dump-token-types>, it would be sufficient to enter
170 B<--dump-tok>, or even B<--dump-t>, to uniquely identify this command.
174 The following parameters concern the files which are read and written.
178 =item B<-h>, B<--help>
180 Show summary of usage and exit.
182 =item B<-o>=filename, B<--outfile>=filename
184 Name of the output file (only if a single input file is being
185 processed). If no output file is specified, and output is not
186 redirected to the standard output (see B<-st>), the output will go to
187 F<filename.tdy>. [Note: - does not redirect to standard output. Use
190 =item B<-st>, B<--standard-output>
192 Perltidy must be able to operate on an arbitrarily large number of files
193 in a single run, with each output being directed to a different output
194 file. Obviously this would conflict with outputting to the single
195 standard output device, so a special flag, B<-st>, is required to
196 request outputting to the standard output. For example,
198 perltidy somefile.pl -st >somefile.new.pl
200 This option may only be used if there is just a single input file.
201 The default is B<-nst> or B<--nostandard-output>.
203 =item B<-se>, B<--standard-error-output>
205 If perltidy detects an error when processing file F<somefile.pl>, its
206 default behavior is to write error messages to file F<somefile.pl.ERR>.
207 Use B<-se> to cause all error messages to be sent to the standard error
208 output stream instead. This directive may be negated with B<-nse>.
209 Thus, you may place B<-se> in a F<.perltidyrc> and override it when
210 desired with B<-nse> on the command line.
212 =item B<-oext>=ext, B<--output-file-extension>=ext
214 Change the extension of the output file to be F<ext> instead of the
215 default F<tdy> (or F<html> in case the -B<-html> option is used).
216 See L<"Specifying File Extensions">.
218 =item B<-opath>=path, B<--output-path>=path
220 When perltidy creates a filename for an output file, by default it merely
221 appends an extension to the path and basename of the input file. This
222 parameter causes the path to be changed to F<path> instead.
224 The path should end in a valid path separator character, but perltidy will try
225 to add one if it is missing.
229 perltidy somefile.pl -opath=/tmp/
231 will produce F</tmp/somefile.pl.tdy>. Otherwise, F<somefile.pl.tdy> will
232 appear in whatever directory contains F<somefile.pl>.
234 If the path contains spaces, it should be placed in quotes.
236 This parameter will be ignored if output is being directed to standard output,
237 or if it is being specified explicitly with the B<-o=s> parameter.
239 =item B<-b>, B<--backup-and-modify-in-place>
241 Modify the input file or files in-place and save the original with the
242 extension F<.bak>. Any existing F<.bak> file will be deleted. See next
243 item for changing the default backup extension, and for eliminating the
244 backup file altogether.
246 B<Please Note>: Writing back to the input file increases the risk of data loss
247 or corruption in the event of a software or hardware malfunction. Before using
248 the B<-b> parameter please be sure to have backups and verify that it works
249 correctly in your environment and operating system.
251 A B<-b> flag will be ignored if input is from standard input or goes to
252 standard output, or if the B<-html> flag is set.
254 In particular, if you want to use both the B<-b> flag and the B<-pbp>
255 (--perl-best-practices) flag, then you must put a B<-nst> flag after the
256 B<-pbp> flag because it contains a B<-st> flag as one of its components,
257 which means that output will go to the standard output stream.
259 =item B<-bext>=ext, B<--backup-file-extension>=ext
261 This parameter serves two purposes: (1) to change the extension of the backup
262 file to be something other than the default F<.bak>, and (2) to indicate
263 that no backup file should be saved.
265 To change the default extension to something other than F<.bak> see
266 L<"Specifying File Extensions">.
268 A backup file of the source is always written, but you can request that it
269 be deleted at the end of processing if there were no errors. This is risky
270 unless the source code is being maintained with a source code control
273 To indicate that the backup should be deleted include one forward slash,
274 B</>, in the extension. If any text remains after the slash is removed
275 it will be used to define the backup file extension (which is always
276 created and only deleted if there were no errors).
278 Here are some examples:
280 Parameter Extension Backup File Treatment
281 <-bext=bak> F<.bak> Keep (same as the default behavior)
282 <-bext='/'> F<.bak> Delete if no errors
283 <-bext='/backup'> F<.backup> Delete if no errors
284 <-bext='original/'> F<.original> Delete if no errors
286 =item B<-bm=s>, B<--backup-method=s>
288 This parameter should not normally be used but is available in the event that
289 problems arise as a transition is made from an older implementation of the
290 backup logic to a newer implementation. The newer implementation is the
291 default and is specified with B<-bm='copy'>. The older implementation is
292 specified with B<-bm='move'>. The difference is that the older implementation
293 made the backup by moving the input file to the backup file, and the newer
294 implementation makes the backup by copying the input file. The newer
295 implementation preserves the file system B<inode> value. This may avoid
296 problems with other software running simultaneously. This change was made
297 as part of issue B<git #103> at github.
299 =item B<-w>, B<--warning-output>
301 Setting B<-w> causes any non-critical warning
302 messages to be reported as errors. These include messages
303 about possible pod problems, possibly bad starting indentation level,
304 and cautions about indirect object usage. The default, B<-nw> or
305 B<--nowarning-output>, is not to include these warnings.
307 =item B<-q>, B<--quiet>
309 Deactivate error messages (for running under an editor).
311 For example, if you use a vi-style editor, such as vim, you may execute
312 perltidy as a filter from within the editor using something like
316 where C<n1,n2> represents the selected text. Without the B<-q> flag,
317 any error message may mess up your screen, so be prepared to use your
320 =item B<-log>, B<--logfile>
322 Save the F<.LOG> file, which has many useful diagnostics. Perltidy always
323 creates a F<.LOG> file, but by default it is deleted unless a program bug is
324 suspected. Setting the B<-log> flag forces the log file to be saved.
326 =item B<-g=n>, B<--logfile-gap=n>
328 Set maximum interval between input code lines in the logfile. This purpose of
329 this flag is to assist in debugging nesting errors. The value of C<n> is
330 optional. If you set the flag B<-g> without the value of C<n>, it will be
331 taken to be 1, meaning that every line will be written to the log file. This
332 can be helpful if you are looking for a brace, paren, or bracket nesting error.
334 Setting B<-g> also causes the logfile to be saved, so it is not necessary to
335 also include B<-log>.
337 If no B<-g> flag is given, a value of 50 will be used, meaning that at least
338 every 50th line will be recorded in the logfile. This helps prevent
339 excessively long log files.
341 Setting a negative value of C<n> is the same as not setting B<-g> at all.
343 =item B<-npro> B<--noprofile>
345 Ignore any F<.perltidyrc> command file. Normally, perltidy looks first in
346 your current directory for a F<.perltidyrc> file of parameters. (The format
347 is described below). If it finds one, it applies those options to the
348 initial default values, and then it applies any that have been defined
349 on the command line. If no F<.perltidyrc> file is found, it looks for one
350 in your home directory.
352 If you set the B<-npro> flag, perltidy will not look for this file.
354 =item B<-pro=filename> or B<--profile=filename>
356 To simplify testing and switching .perltidyrc files, this command may be
357 used to specify a configuration file which will override the default
358 name of .perltidyrc. There must not be a space on either side of the
359 '=' sign. For example, the line
361 perltidy -pro=testcfg
363 would cause file F<testcfg> to be used instead of the
364 default F<.perltidyrc>.
366 A pathname begins with three dots, e.g. ".../.perltidyrc", indicates that
367 the file should be searched for starting in the current directory and
368 working upwards. This makes it easier to have multiple projects each with
369 their own .perltidyrc in their root directories.
371 =item B<-opt>, B<--show-options>
373 Write a list of all options used to the F<.LOG> file.
374 Please see B<--dump-options> for a simpler way to do this.
376 =item B<-f>, B<--force-read-binary>
378 Force perltidy to process binary files. To avoid producing excessive
379 error messages, perltidy skips files identified by the system as non-text.
380 However, valid perl scripts containing binary data may sometimes be identified
381 as non-text, and this flag forces perltidy to process them.
383 =item B<-ast>, B<--assert-tidy>
385 This flag asserts that the input and output code streams are identical, or in
386 other words that the input code is already 'tidy' according to the formatting
387 parameters. If this is not the case, an error message noting this is produced.
388 This error message will cause the process to return a non-zero exit code.
389 The test for this is made by comparing an MD5 hash value for the input and
390 output code streams. This flag has no other effect on the functioning of
391 perltidy. This might be useful for certain code maintenance operations.
392 Note: you will not see this message if you have error messages turned off with the
395 =item B<-asu>, B<--assert-untidy>
397 This flag asserts that the input and output code streams are different, or in
398 other words that the input code is 'untidy' according to the formatting
399 parameters. If this is not the case, an error message noting this is produced.
400 This flag has no other effect on the functioning of perltidy.
402 =item B<-sal=s>, B<--sub-alias-list=s>
404 This flag causes one or more words to be treated the same as if they were the keyword 'sub'. The string B<s> contains one or more alias words, separated by spaces or commas.
408 perltidy -sal='method fun _sub M4'
410 will cause the perltidy to treat the words 'method', 'fun', '_sub' and 'M4' the same as if they were 'sub'. Note that if the alias words are separated by spaces then the string of words should be placed in quotes.
412 Note that several other parameters accept a list of keywords, including 'sub' (see L<"Specifying Block Types">).
413 You do not need to include any sub aliases in these lists. Just include keyword 'sub' if you wish, and all aliases are automatically included.
415 =item B<-gal=s>, B<--grep-alias-list=s>
417 This flag allows a code block following an external 'list operator' function to be formatted as if it followed one of the built-in keywords B<grep>, B<map> or B<sort>. The string B<s> contains the names of one or more such list operators, separated by spaces or commas.
419 By 'list operator' is meant a function which is invoked in the form
423 Perltidy tries to keep code blocks for these functions intact, since they are usually short, and does not automatically break after the closing brace since a list may follow. It also does some special handling of continuation indentation.
425 For example, the code block arguments to functions 'My_grep' and 'My_map' can be given formatting like 'grep' with
427 perltidy -gal='My_grep My_map'
429 By default, the following list operators in List::Util are automatically included:
431 all any first none notall reduce reductions
433 Any operators specified with B<--grep-alias-list> are added to this list.
434 The next parameter can be used to remove words from this default list.
436 =item B<-gaxl=s>, B<--grep-alias-exclusion-list=s>
438 The B<-gaxl=s> flag provides a method for removing any of the default list operators given above
439 by listing them in the string B<s>. To remove all of the default operators use B<-gaxl='*'>.
443 =head1 FORMATTING OPTIONS
451 This flag disables all formatting and causes the input to be copied unchanged
452 to the output except for possible changes in line ending characters and any
453 pre- and post-filters. This can be useful in conjunction with a hierarchical
454 set of F<.perltidyrc> files to avoid unwanted code tidying. See also
455 L<"Skipping Selected Sections of Code"> for a way to avoid tidying specific
458 =item B<-i=n>, B<--indent-columns=n>
460 Use n columns per indentation level (default n=4).
462 =item B<-l=n>, B<--maximum-line-length=n>
464 The default maximum line length is n=80 characters. Perltidy will try
465 to find line break points to keep lines below this length. However, long
466 quotes and side comments may cause lines to exceed this length.
468 The default length of 80 comes from the past when this was the standard CRT
469 screen width. Many programmers prefer to increase this to something like 120.
471 Setting B<-l=0> is equivalent to setting B<-l=(a very large number)>. But this is
472 not recommended because, for example, a very long list will be formatted in a
475 =item B<-vmll>, B<--variable-maximum-line-length>
477 A problem arises using a fixed maximum line length with very deeply nested code
478 and data structures because eventually the amount of leading whitespace used
479 for indicating indentation takes up most or all of the available line width,
480 leaving little or no space for the actual code or data. One solution is to use
481 a very long line length. Another solution is to use the B<-vmll> flag, which
482 basically tells perltidy to ignore leading whitespace when measuring the line
485 To be precise, when the B<-vmll> parameter is set, the maximum line length of a
486 line of code will be M+L*I, where
488 M is the value of --maximum-line-length=M (-l=M), default 80,
489 I is the value of --indent-columns=I (-i=I), default 4,
490 L is the indentation level of the line of code
492 When this flag is set, the choice of breakpoints for a block of code should be
493 essentially independent of its nesting depth. However, the absolute line
494 lengths, including leading whitespace, can still be arbitrarily large. This
495 problem can be avoided by including the next parameter.
497 The default is not to do this (B<-nvmll>).
499 =item B<-wc=n>, B<--whitespace-cycle=n>
501 This flag also addresses problems with very deeply nested code and data
502 structures. When the nesting depth exceeds the value B<n> the leading
503 whitespace will be reduced and start at a depth of 1 again. The result is that
504 blocks of code will shift back to the left rather than moving arbitrarily far
505 to the right. This occurs cyclically to any depth.
507 For example if one level of indentation equals 4 spaces (B<-i=4>, the default),
508 and one uses B<-wc=15>, then if the leading whitespace on a line exceeds about
509 4*15=60 spaces it will be reduced back to 4*1=4 spaces and continue increasing
510 from there. If the whitespace never exceeds this limit the formatting remains
513 The combination of B<-vmll> and B<-wc=n> provides a solution to the problem of
514 displaying arbitrarily deep data structures and code in a finite window,
515 although B<-wc=n> may of course be used without B<-vmll>.
517 The default is not to use this, which can also be indicated using B<-wc=0>.
521 Using tab characters will almost certainly lead to future portability
522 and maintenance problems, so the default and recommendation is not to
523 use them. For those who prefer tabs, however, there are two different
526 Except for possibly introducing tab indentation characters, as outlined
527 below, perltidy does not introduce any tab characters into your file,
528 and it removes any tabs from the code (unless requested not to do so
529 with B<-fws>). If you have any tabs in your comments, quotes, or
530 here-documents, they will remain.
534 =item B<-et=n>, B<--entab-leading-whitespace>
536 This flag causes each B<n> leading space characters produced by the
537 formatting process to be replaced by one tab character. The
538 formatting process itself works with space characters. The B<-et=n> parameter is applied
539 as a last step, after formatting is complete, to convert leading spaces into tabs.
540 Before starting to use tabs, it is essential to first get the indentation
541 controls set as desired without tabs, particularly the two parameters B<--indent-columns=n> (or B<-i=n>) and B<--continuation-indentation=n> (or B<-ci=n>).
543 The value of the integer B<n> can be any value but can be coordinated with the
544 number of spaces used for indentation. For example, B<-et=4 -ci=4 -i=4> will
545 produce one tab for each indentation level and and one for each continuation
546 indentation level. You may want to coordinate the value of B<n> with what your
547 display software assumes for the spacing of a tab.
549 =item B<-t>, B<--tabs>
551 This flag causes one leading tab character to be inserted for each level
552 of indentation. Certain other features are incompatible with this
553 option, and if these options are also given, then a warning message will
554 be issued and this flag will be unset. One example is the B<-lp>
555 option. This flag is retained for backwards compatibility, but
556 if you use tabs, the B<-et=n> flag is recommended. If both B<-t> and
557 B<-et=n> are set, the B<-et=n> is used.
559 =item B<-dt=n>, B<--default-tabsize=n>
561 If the first line of code passed to perltidy contains leading tabs but no
562 tab scheme is specified for the output stream then perltidy must guess how many
563 spaces correspond to each leading tab. This number of spaces B<n>
564 corresponding to each leading tab of the input stream may be specified with
565 B<-dt=n>. The default is B<n=8>.
567 This flag has no effect if a tab scheme is specified for the output stream,
568 because then the input stream is assumed to use the same tab scheme and
569 indentation spaces as for the output stream (any other assumption would lead to
574 =item B<-xs>, B<--extended-syntax>
576 A problem with formatting Perl code is that some modules can introduce new
577 syntax. This flag allows perltidy to handle certain common extensions
578 to the standard syntax without complaint.
580 For example, without this flag a structure such as the following would generate
581 a syntax error and the braces would not be balanced:
583 method deposit( Num $amount) {
584 $self->balance( $self->balance + $amount );
587 For one of the extensions, module Switch::Plain, colons are marked as labels.
588 If you use this module, you may want to also use the B<--nooutdent-labels> flag
589 to prevent lines such as 'default:' from being outdented.
591 This flag is enabled by default but it can be deactivated with B<-nxs>.
592 Probably the only reason to deactivate this flag is to generate more diagnostic
593 messages when debugging a script.
595 For another method of handling extended syntax see the section L<"Skipping Selected Sections of Code">.
597 =item B<-io>, B<--indent-only>
599 This flag is used to deactivate all whitespace and line break changes
600 within non-blank lines of code.
601 When it is in effect, the only change to the script will be
602 to the indentation and to the number of blank lines.
603 And any flags controlling whitespace and newlines will be ignored. You
604 might want to use this if you are perfectly happy with your whitespace
605 and line breaks, and merely want perltidy to handle the indentation.
606 (This also speeds up perltidy by well over a factor of two, so it might be
607 useful when perltidy is merely being used to help find a brace error in
610 Setting this flag is equivalent to setting B<--freeze-newlines> and
611 B<--freeze-whitespace>.
613 If you also want to keep your existing blank lines exactly
614 as they are, you can add B<--freeze-blank-lines>.
616 With this option perltidy is still free to modify the indenting (and
617 outdenting) of code and comments as it normally would. If you also want to
618 prevent long comment lines from being outdented, you can add either B<-noll> or
621 Setting this flag will prevent perltidy from doing any special operations on
622 closing side comments. You may still delete all side comments however when
623 this flag is in effect.
626 =item B<-enc=s>, B<--character-encoding=s>
628 This flag indicates if the input data stream use a character encoding.
629 Perltidy does not look for the encoding directives in the source stream, such
630 as B<use utf8>, and instead relies on this flag to determine the encoding.
631 (Note that perltidy often works on snippets of code rather than complete files
632 so it cannot rely on B<use utf8> directives).
634 The possible values for B<s> are:
636 -enc=none if no encoding is used, or
637 -enc=utf8 for encoding in utf8
638 -enc=guess if perltidy should guess between these two possibilities.
640 The value B<none> causes the stream to be processed without special encoding
641 assumptions. This is appropriate for files which are written in single-byte
642 character encodings such as latin-1.
644 The value B<utf8> causes the stream to be read and written as
645 UTF-8. If the input stream cannot be decoded with this encoding then
646 processing is not done.
648 The value B<guess> tells perltidy to guess between either utf8 encoding or no
649 encoding (meaning one character per byte). The B<guess> option uses the
650 Encode::Guess module which has been found to be reliable at detecting
651 if a file is encoded in utf8 or not.
653 The current default is B<guess>.
655 The abbreviations B<-utf8> or B<-UTF8> are equivalent to B<-enc=utf8>, and the
656 abbreviation B<-guess> is equivalent to B<-enc=guess>. So to process a file
657 named B<file.pl> which is encoded in UTF-8 you can use:
659 perltidy -utf8 file.pl
663 perltidy -guess file.pl
669 since B<-guess> is the default.
671 To process files with an encoding other than UTF-8, it would be necessary to
672 write a short program which calls the Perl::Tidy module with some pre- and
673 post-processing to handle decoding and encoding.
675 =item B<-eos=s>, B<--encode-output-strings=s>
677 This flag was added to resolve an issue involving the interface between
678 Perl::Tidy and calling programs, and in particular B<Code::TidyAll (tidyall)>.
680 If you only run the B<perltidy> binary this flag has no effect. If you run a
681 program which calls the Perl::Tidy module and receives a string in return, then
682 the meaning of the flag is as follows:
688 The setting B<-eos> means Perl::Tidy should encode any string which it decodes.
689 This is the default because it makes perltidy behave well as a filter,
690 and is the correct setting for most programs.
694 The setting B<-neos> means that a string should remain decoded if it was
695 decoded by Perl::Tidy. This is only appropriate if the calling program will
696 handle any needed encoding before outputting the string.
700 The default was changed from B<-neos> to B<-eos> in versions after 20220217.
701 If this change causes a program to start running incorrectly on encoded files,
702 an emergency fix might be to set B<-neos>. Additional information can be found
703 in the man pages for the B<Perl::Tidy> module and also in
704 L<https://github.com/perltidy/perltidy/blob/master/docs/eos_flag.md>.
706 =item B<-gcs>, B<--use-unicode-gcstring>
708 This flag controls whether or not perltidy may use module Unicode::GCString to
709 obtain accurate display widths of wide characters. The default
710 is B<--nouse-unicode-gcstring>.
712 If this flag is set, and text is encoded, perltidy will look for the module
713 Unicode::GCString and, if found, will use it to obtain character display
714 widths. This can improve displayed vertical alignment for files with wide
715 characters. It is a nice feature but it is off by default to avoid conflicting
716 formatting when there are multiple developers. Perltidy installation does not
717 require Unicode::GCString, so users wanting to use this feature need set this
718 flag and also to install Unicode::GCString separately.
720 If this flag is set and perltidy does not find module Unicode::GCString,
721 a warning message will be produced and processing will continue but without
722 the potential benefit provided by the module.
724 Also note that actual vertical alignment depends upon the fonts used by the
725 text display software, so vertical alignment may not be optimal even when
726 Unicode::GCString is used.
728 =item B<-ole=s>, B<--output-line-ending=s>
730 where s=C<win>, C<dos>, C<unix>, or C<mac>. This flag tells perltidy
731 to output line endings for a specific system. Normally,
732 perltidy writes files with the line separator character of the host
733 system. The C<win> and C<dos> flags have an identical result.
735 =item B<-ple>, B<--preserve-line-endings>
737 This flag tells perltidy to write its output files with the same line
738 endings as the input file, if possible. It should work for
739 B<dos>, B<unix>, and B<mac> line endings. It will only work if perltidy
740 input comes from a filename (rather than stdin, for example). If
741 perltidy has trouble determining the input file line ending, it will
742 revert to the default behavior of using the line ending of the host system.
744 =item B<-atnl>, B<--add-terminal-newline>
746 This flag, which is enabled by default, allows perltidy to terminate the last
747 line of the output stream with a newline character, regardless of whether or
748 not the input stream was terminated with a newline character. If this flag is
749 negated, with B<-natnl>, then perltidy will add a terminal newline to the the
750 output stream only if the input stream is terminated with a newline.
752 Negating this flag may be useful for manipulating one-line scripts intended for
753 use on a command line.
755 =item B<-it=n>, B<--iterations=n>
757 This flag causes perltidy to do B<n> complete iterations. The reason for this
758 flag is that code beautification is an iterative process and in some
759 cases the output from perltidy can be different if it is applied a second time.
760 For most purposes the default of B<n=1> should be satisfactory. However B<n=2>
761 can be useful when a major style change is being made, or when code is being
762 beautified on check-in to a source code control system. It has been found to
763 be extremely rare for the output to change after 2 iterations. If a value
764 B<n> is greater than 2 is input then a convergence test will be used to stop
765 the iterations as soon as possible, almost always after 2 iterations. See
766 the next item for a simplified iteration control.
768 This flag has no effect when perltidy is used to generate html.
770 =item B<-conv>, B<--converge>
772 This flag is equivalent to B<-it=4> and is included to simplify iteration
773 control. For all practical purposes one either does or does not want to be
774 sure that the output is converged, and there is no penalty to using a large
775 iteration limit since perltidy will check for convergence and stop iterating as
776 soon as possible. The default is B<-nconv> (no convergence check). Using
777 B<-conv> will approximately double run time since typically one extra iteration
778 is required to verify convergence. No extra iterations are required if no new
779 line breaks are made, and two extra iterations are occasionally needed when
780 reformatting complex code structures, such as deeply nested ternary statements.
784 =head2 Code Indentation Control
788 =item B<-ci=n>, B<--continuation-indentation=n>
790 Continuation indentation is extra indentation spaces applied when
791 a long line is broken. The default is n=2, illustrated here:
794 ( $max_index_to_go >= 0 ) ? $levels_to_go[0] : $last_output_level;
796 The same example, with n=0, is a little harder to read:
799 ( $max_index_to_go >= 0 ) ? $levels_to_go[0] : $last_output_level;
801 The value given to B<-ci> is also used by some commands when a small
802 space is required. Examples are commands for outdenting labels,
803 B<-ola>, and control keywords, B<-okw>.
805 When default values are not used, it is recommended that either
807 (1) the value B<n> given with B<-ci=n> be no more than about one-half of the
808 number of spaces assigned to a full indentation level on the B<-i=n> command, or
810 (2) the flag B<-extended-continuation-indentation> is used (see next section).
812 =item B<-xci>, B<--extended-continuation-indentation>
814 This flag allows perltidy to use some improvements which have been made to its
815 indentation model. One of the things it does is "extend" continuation
816 indentation deeper into structures, hence the name. The improved indentation
817 is particularly noticeable when the flags B<-ci=n> and B<-i=n> use the same value of
818 B<n>. There are no significant disadvantages to using this flag, but to avoid
819 disturbing existing formatting the default is not to use it, B<-nxci>.
821 Please see the section L<"B<-pbp>, B<--perl-best-practices>"> for an example of
822 how this flag can improve the formatting of ternary statements. It can also
823 improve indentation of some multi-line qw lists as shown below.
828 AntiqueWhite3 Bisque1 Bisque2 Bisque3 Bisque4
829 SlateBlue3 RoyalBlue1 SteelBlue2 DeepSkyBlue3
832 LightBlue1 DarkSlateGray1 Aquamarine2 DarkSeaGreen2
833 SeaGreen1 Yellow1 IndianRed1 IndianRed2 Tan1 Tan4
840 AntiqueWhite3 Bisque1 Bisque2 Bisque3 Bisque4
841 SlateBlue3 RoyalBlue1 SteelBlue2 DeepSkyBlue3
844 LightBlue1 DarkSlateGray1 Aquamarine2 DarkSeaGreen2
845 SeaGreen1 Yellow1 IndianRed1 IndianRed2 Tan1 Tan4
849 =item B<-sil=n> B<--starting-indentation-level=n>
851 By default, perltidy examines the input file and tries to determine the
852 starting indentation level. While it is often zero, it may not be
853 zero for a code snippet being sent from an editing session.
855 To guess the starting indentation level perltidy simply assumes that
856 indentation scheme used to create the code snippet is the same as is being used
857 for the current perltidy process. This is the only sensible guess that can be
858 made. It should be correct if this is true, but otherwise it probably won't.
859 For example, if the input script was written with -i=2 and the current perltidy
860 flags have -i=4, the wrong initial indentation will be guessed for a code
861 snippet which has non-zero initial indentation. Likewise, if an entabbing
862 scheme is used in the input script and not in the current process then the
863 guessed indentation will be wrong.
865 If the default method does not work correctly, or you want to change the
866 starting level, use B<-sil=n>, to force the starting level to be n.
868 =item B<List indentation> using B<--line-up-parentheses>, B<-lp> or B<--extended--line-up-parentheses> , B<-xlp>
870 These flags provide an alternative indentation method for list data. The
871 original flag for this is B<-lp>, but it has some limitations (explained below)
872 which are avoided with the newer B<-xlp> flag. So B<-xlp> is probably the better
873 choice for new work, but the B<-lp> flag is retained to minimize changes to
875 If you enter both B<-lp> and B<-xlp>, then B<-xlp> will be used.
878 In the default indentation method perltidy indents lists with 4 spaces, or
879 whatever value is specified with B<-i=n>. Here is a small list formatted in
884 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
885 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
888 The B<-lp> or B<-xlp> flags add extra indentation to cause the data to begin
889 past the opening parentheses of a sub call or list, or opening square bracket
890 of an anonymous array, or opening curly brace of an anonymous hash. With this
891 option, the above list would become:
893 # perltidy -lp or -xlp
895 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
896 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
899 If the available line length (see B<-l=n> ) does not permit this much
900 space, perltidy will use less. For alternate placement of the
901 closing paren, see the next section.
903 These flags have no effect on code BLOCKS, such as if/then/else blocks,
904 which always use whatever is specified with B<-i=n>.
906 Some limitations on these flags are:
912 A limitation on B<-lp>, but not B<-xlp>, occurs in situations where perltidy
913 does not have complete freedom to choose line breaks. Then it may temporarily revert
914 to its default indentation method. This can occur for example if there are
915 blank lines, block comments, multi-line quotes, or side comments between the
916 opening and closing parens, braces, or brackets. It will also occur if a
917 multi-line anonymous sub occurs within a container since that will impose
918 specific line breaks (such as line breaks after statements).
922 For both the B<-lp> and B<-xlp> flags, any parameter which significantly
923 restricts the ability of perltidy to choose newlines will conflict with these
924 flags and will cause them to be deactivated. These include B<-io>, B<-fnl>,
925 B<-nanl>, and B<-ndnl>.
929 The B<-lp> and B<-xlp> options may not be used together with the B<-t> tabs option.
930 They may, however, be used with the B<-et=n> tab method
934 There are some potential disadvantages of this indentation method compared to
935 the default method that should be noted:
941 The available line length can quickly be used up if variable names are
942 long. This can cause deeply nested code to quickly reach the line length
943 limit, and become badly formatted, much sooner than would occur with the
944 default indentation method.
948 Since the indentation depends on the lengths of variable names, small
949 changes in variable names can cause changes in indentation over many lines in a
950 file. This means that minor name changes can produce significant file
951 differences. This can be annoying and does not occur with the default
956 Some things that can be done to minimize these problems are:
962 Increase B<--maximum-line-length=n> above the default B<n=80> characters if
967 If you use B<-xlp> then long side comments can limit the indentation over
968 multiple lines. Consider adding the flag B<--ignore-side-comment-lengths> to
969 prevent this, or minimizing the use of side comments.
973 Apply this style in a limited way. By default, it applies to all list
974 containers (not just lists in parentheses). The next section describes how to
975 limit this style to, for example, just function calls. The default indentation
976 method will be applied elsewhere.
980 =item B<-lpil=s>, B<--line-up-parentheses-inclusion-list> and B<-lpxl=s>, B<--line-up-parentheses-exclusion-list>
982 The following discussion is written for B<-lp> but applies equally to the newer B<-xlp> version.
983 By default, the B<-lp> flag applies to as many containers as possible.
984 The set of containers to which the B<-lp> style applies can be reduced by
985 either one of these two flags:
987 Use B<-lpil=s> to specify the containers to which B<-lp> applies, or
989 use B<-lpxl=s> to specify the containers to which B<-lp> does NOT apply.
991 Only one of these two flags may be used. Both flags can achieve the same
992 result, but the B<-lpil=s> flag is much easier to describe and use and is
993 recommended. The B<-lpxl=s> flag was the original implementation and is
994 only retained for backwards compatibility.
996 This list B<s> for these parameters is a string with space-separated items.
997 Each item consists of up to three pieces of information in this order: (1) an
998 optional letter code (2) a required container type, and (3) an optional numeric
1001 The only required piece of information is a container type, which is one of
1002 '(', '[', or '{'. For example the string
1006 means use -lp formatting only on lists within parentheses, not lists in square-brackets or braces.
1007 The same thing could alternatively be specified with
1011 which says to exclude lists within square-brackets and braces. So what remains is lists within parentheses.
1013 A second optional item of information which can be given for parentheses is an alphanumeric
1014 letter which is used to limit the selection further depending on the type of
1015 token immediately before the paren. The possible letters are currently 'k',
1016 'K', 'f', 'F', 'w', and 'W', with these meanings for matching whatever precedes an opening paren:
1018 'k' matches if the previous nonblank token is a perl built-in keyword (such as 'if', 'while'),
1019 'K' matches if 'k' does not, meaning that the previous token is not a keyword.
1020 'f' matches if the previous token is a function other than a keyword.
1021 'F' matches if 'f' does not.
1022 'w' matches if either 'k' or 'f' match.
1023 'W' matches if 'w' does not.
1029 means only apply -lp to function calls, and
1033 means only apply -lp to parenthesized lists which follow a function or a keyword.
1035 This last example could alternatively be written using the B<-lpxl=s> flag as
1039 which says exclude B<-lp> for lists within square-brackets, braces, and parens NOT preceded by
1040 a keyword or function. Clearly, the B<-lpil=s> method is easier to understand.
1042 An optional numeric code may follow any of the container types to further refine the selection based
1043 on container contents. The numeric codes are:
1045 '0' or blank: no check on contents is made
1046 '1' exclude B<-lp> unless the contents is a simple list without sublists
1047 '2' exclude B<-lp> unless the contents is a simple list without sublists, without
1048 code blocks, and without ternary operators
1054 means only apply -lp to function call lists which do not contain any sublists,
1055 code blocks or ternary expressions.
1057 =item B<-cti=n>, B<--closing-token-indentation>
1059 The B<-cti=n> flag controls the indentation of a line beginning with
1060 a C<)>, C<]>, or a non-block C<}>. Such a line receives:
1062 -cti = 0 no extra indentation (default)
1063 -cti = 1 extra indentation such that the closing token
1064 aligns with its opening token.
1065 -cti = 2 one extra indentation level if the line looks like:
1067 -cti = 3 one extra indentation level always
1069 The flags B<-cti=1> and B<-cti=2> work well with the B<-lp> flag (previous
1072 # perltidy -lp -cti=1
1074 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
1075 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
1078 # perltidy -lp -cti=2
1080 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
1081 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
1084 These flags are merely hints to the formatter and they may not always be
1085 followed. In particular, if -lp is not being used, the indentation for
1086 B<cti=1> is constrained to be no more than one indentation level.
1088 If desired, this control can be applied independently to each of the
1089 closing container token types. In fact, B<-cti=n> is merely an
1090 abbreviation for B<-cpi=n -csbi=n -cbi=n>, where:
1091 B<-cpi> or B<--closing-paren-indentation> controls B<)>'s,
1092 B<-csbi> or B<--closing-square-bracket-indentation> controls B<]>'s,
1093 B<-cbi> or B<--closing-brace-indentation> controls non-block B<}>'s.
1095 =item B<-icp>, B<--indent-closing-paren>
1097 The B<-icp> flag is equivalent to
1098 B<-cti=2>, described in the previous section. The B<-nicp> flag is
1099 equivalent B<-cti=0>. They are included for backwards compatibility.
1101 =item B<-icb>, B<--indent-closing-brace>
1103 The B<-icb> option gives one extra level of indentation to a brace which
1104 terminates a code block . For example,
1113 The default is not to do this, indicated by B<-nicb>.
1116 =item B<-nib>, B<--non-indenting-braces>
1118 Normally, lines of code contained within a pair of block braces receive one
1119 additional level of indentation. This flag, which is enabled by default,
1120 causes perltidy to look for
1121 opening block braces which are followed by a special side comment. This special
1122 side comment is B<#<<<> by default. If found, the code between this opening brace and its
1123 corresponding closing brace will not be given the normal extra indentation
1126 { #<<< a closure to contain lexical vars
1128 my $var; # this line does not get one level of indentation
1133 # this line does not 'see' $var;
1135 This can be useful, for example, when combining code from different files.
1136 Different sections of code can be placed within braces to keep their lexical
1137 variables from being visible to the end of the file. To keep the new braces
1138 from causing all of their contained code to be indented if you run perltidy,
1139 and possibly introducing new line breaks in long lines, you can mark the
1140 opening braces with this special side comment.
1142 Only the opening brace needs to be marked, since perltidy knows where the
1143 closing brace is. Braces contained within marked braces may also be marked
1146 If your code happens to have some opening braces followed by '#<<<', and you
1147 don't want this behavior, you can use B<-nnib> to deactivate it. To make it
1148 easy to remember, the default string is the same as the string for starting a
1149 B<format-skipping> section. There is no confusion because in that case it is
1150 for a block comment rather than a side-comment.
1152 The special side comment can be changed with the next parameter.
1155 =item B<-nibp=s>, B<--non-indenting-brace-prefix=s>
1157 The B<-nibp=string> parameter may be used to change the marker for
1158 non-indenting braces. The default is equivalent to -nibp='#<<<'. The string
1159 that you enter must begin with a # and should be in quotes as necessary to get
1160 past the command shell of your system. This string is the leading text of a
1161 regex pattern that is constructed by appending pre-pending a '^' and appending
1162 a'\s', so you must also include backslashes for characters to be taken
1163 literally rather than as patterns.
1165 For example, to match the side comment '#++', the parameter would be
1170 =item B<-olq>, B<--outdent-long-quotes>
1172 When B<-olq> is set, lines which is a quoted string longer than the
1173 value B<maximum-line-length> will have their indentation removed to make
1174 them more readable. This is the default. To prevent such out-denting,
1175 use B<-nolq> or B<--nooutdent-long-lines>.
1177 =item B<-oll>, B<--outdent-long-lines>
1179 This command is equivalent to B<--outdent-long-quotes> and
1180 B<--outdent-long-comments>, and it is included for compatibility with previous
1181 versions of perltidy. The negation of this also works, B<-noll> or
1182 B<--nooutdent-long-lines>, and is equivalent to setting B<-nolq> and B<-nolc>.
1184 =item B<Outdenting Labels:> B<-ola>, B<--outdent-labels>
1186 This command will cause labels to be outdented by 2 spaces (or whatever B<-ci>
1187 has been set to), if possible. This is the default. For example:
1190 LOOP: while ( $i = <FOTOS> ) {
1196 Use B<-nola> to not outdent labels. To control line breaks after labels see L<"-bal=n, --break-after-labels=n">.
1198 =item B<Outdenting Keywords>
1202 =item B<-okw>, B<--outdent-keywords>
1204 The command B<-okw> will cause certain leading control keywords to
1205 be outdented by 2 spaces (or whatever B<-ci> has been set to), if
1206 possible. By default, these keywords are C<redo>, C<next>, C<last>,
1207 C<goto>, and C<return>. The intention is to make these control keywords
1208 easier to see. To change this list of keywords being outdented, see
1211 For example, using C<perltidy -okw> on the previous example gives:
1214 LOOP: while ( $i = <FOTOS> ) {
1220 The default is not to do this.
1222 =item B<Specifying Outdented Keywords:> B<-okwl=string>, B<--outdent-keyword-list=string>
1224 This command can be used to change the keywords which are outdented with
1225 the B<-okw> command. The parameter B<string> is a required list of perl
1226 keywords, which should be placed in quotes if there are more than one.
1227 By itself, it does not cause any outdenting to occur, so the B<-okw>
1228 command is still required.
1230 For example, the commands C<-okwl="next last redo goto" -okw> will cause
1231 those four keywords to be outdented. It is probably simplest to place
1232 any B<-okwl> command in a F<.perltidyrc> file.
1238 =head2 Whitespace Control
1240 Whitespace refers to the blank space between variables, operators,
1241 and other code tokens.
1245 =item B<-fws>, B<--freeze-whitespace>
1247 This flag causes your original whitespace to remain unchanged, and
1248 causes the rest of the whitespace commands in this section, the
1249 Code Indentation section, and
1250 the Comment Control section to be ignored.
1252 =item B<Tightness of curly braces, parentheses, and square brackets>
1254 Here the term "tightness" will mean the closeness with which
1255 pairs of enclosing tokens, such as parentheses, contain the quantities
1256 within. A numerical value of 0, 1, or 2 defines the tightness, with
1257 0 being least tight and 2 being most tight. Spaces within containers
1258 are always symmetric, so if there is a space after a C<(> then there
1259 will be a space before the corresponding C<)>.
1261 The B<-pt=n> or B<--paren-tightness=n> parameter controls the space within
1262 parens. The example below shows the effect of the three possible
1263 values, 0, 1, and 2:
1265 if ( ( my $len_tab = length( $tabstr ) ) > 0 ) { # -pt=0
1266 if ( ( my $len_tab = length($tabstr) ) > 0 ) { # -pt=1 (default)
1267 if ((my $len_tab = length($tabstr)) > 0) { # -pt=2
1269 When n is 0, there is always a space to the right of a '(' and to the left
1270 of a ')'. For n=2 there is never a space. For n=1, the default, there
1271 is a space unless the quantity within the parens is a single token, such
1272 as an identifier or quoted string.
1274 Likewise, the parameter B<-sbt=n> or B<--square-bracket-tightness=n>
1275 controls the space within square brackets, as illustrated below.
1277 $width = $col[ $j + $k ] - $col[ $j ]; # -sbt=0
1278 $width = $col[ $j + $k ] - $col[$j]; # -sbt=1 (default)
1279 $width = $col[$j + $k] - $col[$j]; # -sbt=2
1281 Curly braces which do not contain code blocks are controlled by
1282 the parameter B<-bt=n> or B<--brace-tightness=n>.
1284 $obj->{ $parsed_sql->{ 'table' }[0] }; # -bt=0
1285 $obj->{ $parsed_sql->{'table'}[0] }; # -bt=1 (default)
1286 $obj->{$parsed_sql->{'table'}[0]}; # -bt=2
1288 And finally, curly braces which contain blocks of code are controlled by the
1289 parameter B<-bbt=n> or B<--block-brace-tightness=n> as illustrated in the
1292 %bf = map { $_ => -M $_ } grep { /\.deb$/ } dirents '.'; # -bbt=0 (default)
1293 %bf = map { $_ => -M $_ } grep {/\.deb$/} dirents '.'; # -bbt=1
1294 %bf = map {$_ => -M $_} grep {/\.deb$/} dirents '.'; # -bbt=2
1296 To simplify input in the case that all of the tightness flags have the same
1297 value <n>, the parameter <-act=n> or B<--all-containers-tightness=n> is an
1298 abbreviation for the combination <-pt=n -sbt=n -bt=n -bbt=n>.
1301 =item B<-tso>, B<--tight-secret-operators>
1303 The flag B<-tso> causes certain perl token sequences (secret operators)
1304 which might be considered to be a single operator to be formatted "tightly"
1305 (without spaces). The operators currently modified by this flag are:
1307 0+ +0 ()x!! ~~<> ,=> =( )=
1309 For example the sequence B<0 +>, which converts a string to a number,
1310 would be formatted without a space: B<0+> when the B<-tso> flag is set. This
1311 flag is off by default.
1313 =item B<-sts>, B<--space-terminal-semicolon>
1315 Some programmers prefer a space before all terminal semicolons. The
1316 default is for no such space, and is indicated with B<-nsts> or
1317 B<--nospace-terminal-semicolon>.
1320 $i = 1; # -nsts (default)
1322 =item B<-sfs>, B<--space-for-semicolon>
1324 Semicolons within B<for> loops may sometimes be hard to see,
1325 particularly when commas are also present. This option places spaces on
1326 both sides of these special semicolons, and is the default. Use
1327 B<-nsfs> or B<--nospace-for-semicolon> to deactivate it.
1329 for ( @a = @$ap, $u = shift @a ; @a ; $u = $v ) { # -sfs (default)
1330 for ( @a = @$ap, $u = shift @a; @a; $u = $v ) { # -nsfs
1332 =item B<-asc>, B<--add-semicolons>
1334 Setting B<-asc> allows perltidy to add any missing optional semicolon at the end
1335 of a line which is followed by a closing curly brace on the next line. This
1336 is the default, and may be deactivated with B<-nasc> or B<--noadd-semicolons>.
1338 =item B<-dsm>, B<--delete-semicolons>
1340 Setting B<-dsm> allows perltidy to delete extra semicolons which are
1341 simply empty statements. This is the default, and may be deactivated
1342 with B<-ndsm> or B<--nodelete-semicolons>. (Such semicolons are not
1343 deleted, however, if they would promote a side comment to a block
1346 =item B<-aws>, B<--add-whitespace>
1348 Setting this option allows perltidy to add certain whitespace to improve
1349 code readability. This is the default. If you do not want any
1350 whitespace added, but are willing to have some whitespace deleted, use
1351 B<-naws>. (Use B<-fws> to leave whitespace completely unchanged).
1353 =item B<-dws>, B<--delete-old-whitespace>
1355 Setting this option allows perltidy to remove some old whitespace
1356 between characters, if necessary. This is the default. If you
1357 do not want any old whitespace removed, use B<-ndws> or
1358 B<--nodelete-old-whitespace>.
1360 =item B<Detailed whitespace controls around tokens>
1362 For those who want more detailed control over the whitespace around
1363 tokens, there are four parameters which can directly modify the default
1364 whitespace rules built into perltidy for any token. They are:
1366 B<-wls=s> or B<--want-left-space=s>,
1368 B<-nwls=s> or B<--nowant-left-space=s>,
1370 B<-wrs=s> or B<--want-right-space=s>,
1372 B<-nwrs=s> or B<--nowant-right-space=s>.
1374 These parameters are each followed by a quoted string, B<s>, containing a
1375 list of token types. No more than one of each of these parameters
1376 should be specified, because repeating a command-line parameter
1377 always overwrites the previous one before perltidy ever sees it.
1379 To illustrate how these are used, suppose it is desired that there be no
1380 space on either side of the token types B<= + - / *>. The following two
1381 parameters would specify this desire:
1383 -nwls="= + - / *" -nwrs="= + - / *"
1385 (Note that the token types are in quotes, and that they are separated by
1386 spaces). With these modified whitespace rules, the following line of math:
1388 $root = -$b + sqrt( $b * $b - 4. * $a * $c ) / ( 2. * $a );
1392 $root=-$b+sqrt( $b*$b-4.*$a*$c )/( 2.*$a );
1394 These parameters should be considered to be hints to perltidy rather
1395 than fixed rules, because perltidy must try to resolve conflicts that
1396 arise between them and all of the other rules that it uses. One
1397 conflict that can arise is if, between two tokens, the left token wants
1398 a space and the right one doesn't. In this case, the token not wanting
1399 a space takes priority.
1401 It is necessary to have a list of all token types in order to create
1402 this type of input. Such a list can be obtained by the command
1403 B<--dump-token-types>. Also try the B<-D> flag on a short snippet of code
1404 and look at the .DEBUG file to see the tokenization.
1406 B<WARNING> Be sure to put these tokens in quotes to avoid having them
1407 misinterpreted by your command shell.
1409 =item B<Note1: Perltidy does always follow whitespace controls>
1411 The various parameters controlling whitespace within a program are requests which perltidy follows as well as possible, but there are a number of situations where changing whitespace could change program behavior and is not done. Some of these are obvious; for example, we should not remove the space between the two plus symbols in '$x+ +$y' to avoid creating a '++' operator. Some are more subtle and involve the whitespace around bareword symbols and locations of possible filehandles. For example, consider the problem of formatting the following subroutine:
1418 Suppose the user requests that / signs have a space to the left but not to the right. Perltidy will refuse to do this, but if this were done the result would be
1425 If formatted in this way, the program will not run (at least with recent versions of perl) because the $x is taken to be a filehandle and / is assumed to start a quote. In a complex program, there might happen to be a / which terminates the multiline quote without a syntax error, allowing the program to run, but not as intended.
1427 Related issues arise with other binary operator symbols, such as + and -, and in older versions of perl there could be problems with ternary operators. So to avoid changing program behavior, perltidy has the simple rule that whitespace around possible filehandles is left unchanged. Likewise, whitespace around barewords is left unchanged. The reason is that if the barewords are defined in other modules, or in code that has not even been written yet, perltidy will not have seen their prototypes and must treat them cautiously.
1429 In perltidy this is implemented in the tokenizer by marking token following a
1430 B<print> keyword as a special type B<Z>. When formatting is being done,
1431 whitespace following this token type is generally left unchanged as a precaution
1432 against changing program behavior. This is excessively conservative but simple
1433 and easy to implement. Keywords which are treated similarly to B<print> include
1434 B<printf>, B<sort>, B<exec>, B<system>. Changes in spacing around parameters
1435 following these keywords may have to be made manually. For example, the space,
1436 or lack of space, after the parameter $foo in the following line will be
1437 unchanged in formatting.
1442 To find if a token is of type B<Z> you can use B<perltidy -DEBUG>. For the
1443 first line above the result is
1448 which shows that B<system> is type B<k> (keyword) and $foo is type B<Z>.
1450 =item B<Note2: Perltidy's whitespace rules are not perfect>
1452 Despite these precautions, it is still possible to introduce syntax errors with
1453 some asymmetric whitespace rules, particularly when call parameters are not
1454 placed in containing parens or braces. For example, the following two lines will
1455 be parsed by perl without a syntax error:
1457 # original programming, syntax ok
1458 my @newkeys = map $_-$nrecs+@data, @oldkeys;
1460 # perltidy default, syntax ok
1461 my @newkeys = map $_ - $nrecs + @data, @oldkeys;
1463 But the following will give a syntax error:
1465 # perltidy -nwrs='-'
1466 my @newkeys = map $_ -$nrecs + @data, @oldkeys;
1468 For another example, the following two lines will be parsed without syntax error:
1470 # original programming, syntax ok
1471 for my $severity ( reverse $SEVERITY_LOWEST+1 .. $SEVERITY_HIGHEST ) { ... }
1473 # perltidy default, syntax ok
1474 for my $severity ( reverse $SEVERITY_LOWEST + 1 .. $SEVERITY_HIGHEST ) { ... }
1476 But the following will give a syntax error:
1478 # perltidy -nwrs='+', syntax error:
1479 for my $severity ( reverse $SEVERITY_LOWEST +1 .. $SEVERITY_HIGHEST ) { ... }
1481 To avoid subtle parsing problems like this, it is best to avoid spacing a
1482 binary operator asymmetrically with a space on the left but not on the right.
1484 =item B<Space between specific keywords and opening paren>
1486 When an opening paren follows a Perl keyword, no space is introduced after the
1487 keyword, unless it is (by default) one of these:
1489 my local our and or xor eq ne if else elsif until unless
1490 while for foreach return switch case given when
1492 These defaults can be modified with two commands:
1494 B<-sak=s> or B<--space-after-keyword=s> adds keywords.
1496 B<-nsak=s> or B<--nospace-after-keyword=s> removes keywords.
1498 where B<s> is a list of keywords (in quotes if necessary). For example,
1500 my ( $a, $b, $c ) = @_; # default
1501 my( $a, $b, $c ) = @_; # -nsak="my local our"
1503 The abbreviation B<-nsak='*'> is equivalent to including all of the
1504 keywords in the above list.
1506 When both B<-nsak=s> and B<-sak=s> commands are included, the B<-nsak=s>
1507 command is executed first. For example, to have space after only the
1508 keywords (my, local, our) you could use B<-nsak="*" -sak="my local our">.
1510 To put a space after all keywords, see the next item.
1512 =item B<Space between all keywords and opening parens>
1514 When an opening paren follows a function or keyword, no space is introduced
1515 after the keyword except for the keywords noted in the previous item. To
1516 always put a space between a function or keyword and its opening paren,
1519 B<-skp> or B<--space-keyword-paren>
1521 You may also want to use the flag B<-sfp> (next item) too.
1523 =item B<Space between all function names and opening parens>
1525 When an opening paren follows a function the default and recommended formatting
1526 is not to introduce a space. To cause a space to be introduced use:
1528 B<-sfp> or B<--space-function-paren>
1530 myfunc( $a, $b, $c ); # default
1531 myfunc ( $a, $b, $c ); # -sfp
1533 You will probably also want to use the flag B<-skp> (previous item) too.
1535 The reason this is not recommended is that spacing a function paren can make a
1536 program vulnerable to parsing problems by Perl. For example, the following
1537 two-line program will run as written but will have a syntax error if
1538 reformatted with -sfp:
1540 if ( -e filename() ) { print "I'm here\n"; }
1541 sub filename { return $0 }
1543 In this particular case the syntax error can be removed if the line order is
1544 reversed, so that Perl parses 'sub filename' first.
1546 =item B<-fpva> or B<--function-paren-vertical-alignment>
1548 A side-effect of using the B<-sfp> flag is that the parens may become vertically
1549 aligned. For example,
1552 myfun ( $aaa, $b, $cc );
1553 mylongfun ( $a, $b, $c );
1555 This is the default behavior. To prevent this alignment use B<-nfpva>:
1557 # perltidy -sfp -nfpva
1558 myfun ( $aaa, $b, $cc );
1559 mylongfun ( $a, $b, $c );
1561 =item B<-spp=n> or B<--space-prototype-paren=n>
1563 This flag can be used to control whether a function prototype is preceded by a space. For example, the following prototype does not have a space.
1567 This integer B<n> may have the value 0, 1, or 2 as follows:
1569 -spp=0 means no space before the paren
1570 -spp=1 means follow the example of the source code [DEFAULT]
1571 -spp=2 means always put a space before the paren
1573 The default is B<-spp=1>, meaning that a space will be used if and only if there is one in the source code. Given the above line of code, the result of
1574 applying the different options would be:
1576 sub usage(); # n=0 [no space]
1577 sub usage(); # n=1 [default; follows input]
1578 sub usage (); # n=2 [space]
1580 =item B<-kpit=n> or B<--keyword-paren-inner-tightness=n>
1582 The space inside of an opening paren, which itself follows a certain keyword,
1583 can be controlled by this parameter. The space on the inside of the
1584 corresponding closing paren will be treated in the same (balanced) manner.
1585 This parameter has precedence over any other paren spacing rules. The values
1586 of B<n> are as follows:
1588 -kpit=0 means always put a space (not tight)
1589 -kpit=1 means ignore this parameter [default]
1590 -kpit=2 means never put a space (tight)
1592 To illustrate, the following snippet is shown formatted in three ways:
1594 if ( seek( DATA, 0, 0 ) ) { ... } # perltidy (default)
1595 if (seek(DATA, 0, 0)) { ... } # perltidy -pt=2
1596 if ( seek(DATA, 0, 0) ) { ... } # perltidy -pt=2 -kpit=0
1598 In the second case the -pt=2 parameter makes all of the parens tight. In the
1599 third case the -kpit=0 flag causes the space within the 'if' parens to have a
1600 space, since 'if' is one of the keywords to which the -kpit flag applies by
1601 default. The remaining parens are still tight because of the -pt=2 parameter.
1603 The set of keywords to which this parameter applies are by default are:
1605 if elsif unless while until for foreach
1607 These can be changed with the parameter B<-kpitl=s> described in the next section.
1610 =item B<-kpitl=string> or B<--keyword-paren-inner-tightness=string>
1612 This command can be used to change the keywords to which the the B<-kpit=n>
1613 command applies. The parameter B<string> is a required list either keywords or
1614 functions, which should be placed in quotes if there are more than one. By
1615 itself, this parameter does not cause any change in spacing, so the B<-kpit=n>
1616 command is still required.
1618 For example, the commands C<-kpitl="if else while" -kpit=2> will cause the just
1619 the spaces inside parens following 'if', 'else', and 'while' keywords to
1620 follow the tightness value indicated by the B<-kpit=2> flag.
1622 =item B<-lop> or B<--logical-padding>
1624 In the following example some extra space has been inserted on the second
1625 line between the two open parens. This extra space is called "logical padding"
1626 and is intended to help align similar things vertically in some logical
1627 or ternary expressions.
1629 # perltidy [default formatting]
1634 && ( $a->{'title'} eq $b->{'title'} )
1635 && ( $a->{'href'} eq $b->{'href'} ) );
1637 Note that this is considered to be a different operation from "vertical
1638 alignment" because space at just one line is being adjusted, whereas in
1639 "vertical alignment" the spaces at all lines are being adjusted. So it sort of
1640 a local version of vertical alignment.
1642 Here is an example involving a ternary operator:
1644 # perltidy [default formatting]
1651 This behavior is controlled with the flag B<--logical-padding>, which is set
1652 'on' by default. If it is not desired it can be turned off using
1653 B<--nological-padding> or B<-nlop>. The above two examples become, with
1661 && ( $a->{'title'} eq $b->{'title'} )
1662 && ( $a->{'href'} eq $b->{'href'} ) );
1672 =item B<Trimming whitespace around C<qw> quotes>
1674 B<-tqw> or B<--trim-qw> provide the default behavior of trimming
1675 spaces around multi-line C<qw> quotes and indenting them appropriately.
1677 B<-ntqw> or B<--notrim-qw> cause leading and trailing whitespace around
1678 multi-line C<qw> quotes to be left unchanged. This option will not
1679 normally be necessary, but was added for testing purposes, because in
1680 some versions of perl, trimming C<qw> quotes changes the syntax tree.
1682 =item B<-sbq=n> or B<--space-backslash-quote=n>
1689 can confuse syntax highlighters unless a space is included between the backslash and the single or double quotation mark.
1691 this can be controlled with the value of B<n> as follows:
1693 -sbq=0 means no space between the backslash and quote
1694 -sbq=1 means follow the example of the source code
1695 -sbq=2 means always put a space between the backslash and quote
1697 The default is B<-sbq=1>, meaning that a space will be used if there is one in the source code.
1699 =item B<Trimming trailing whitespace from lines of POD>
1701 B<-trp> or B<--trim-pod> will remove trailing whitespace from lines of POD.
1702 The default is not to do this.
1706 =head2 Comment Controls
1708 Perltidy has a number of ways to control the appearance of both block comments
1709 and side comments. The term B<block comment> here refers to a full-line
1710 comment, whereas B<side comment> will refer to a comment which appears on a
1711 line to the right of some code.
1715 =item B<-ibc>, B<--indent-block-comments>
1717 Block comments normally look best when they are indented to the same
1718 level as the code which follows them. This is the default behavior, but
1719 you may use B<-nibc> to keep block comments left-justified. Here is an
1722 # this comment is indented (-ibc, default)
1723 if ($task) { yyy(); }
1725 The alternative is B<-nibc>:
1727 # this comment is not indented (-nibc)
1728 if ($task) { yyy(); }
1730 See also the next item, B<-isbc>, as well as B<-sbc>, for other ways to
1731 have some indented and some outdented block comments.
1733 =item B<-isbc>, B<--indent-spaced-block-comments>
1735 If there is no leading space on the line, then the comment will not be
1736 indented, and otherwise it may be.
1738 If both B<-ibc> and B<-isbc> are set, then B<-isbc> takes priority.
1740 =item B<-olc>, B<--outdent-long-comments>
1742 When B<-olc> is set, lines which are full-line (block) comments longer
1743 than the value B<maximum-line-length> will have their indentation
1744 removed. This is the default; use B<-nolc> to prevent outdenting.
1746 =item B<-msc=n>, B<--minimum-space-to-comment=n>
1748 Side comments look best when lined up several spaces to the right of
1749 code. Perltidy will try to keep comments at least n spaces to the
1750 right. The default is n=4 spaces.
1752 =item B<-fpsc=n>, B<--fixed-position-side-comment=n>
1754 This parameter tells perltidy to line up side comments in column number B<n>
1755 whenever possible. The default, n=0, will not do this.
1757 =item B<-iscl>, B<--ignore-side-comment-lengths>
1759 This parameter causes perltidy to ignore the length of side comments when
1760 setting line breaks. The default, B<-niscl>, is to include the length of
1761 side comments when breaking lines to stay within the length prescribed
1762 by the B<-l=n> maximum line length parameter. For example, the following
1763 long single line would remain intact with -l=80 and -iscl:
1765 perltidy -l=80 -iscl
1766 $vmsfile =~ s/;[\d\-]*$//; # Clip off version number; we can use a newer version as well
1768 whereas without the -iscl flag the line will be broken:
1771 $vmsfile =~ s/;[\d\-]*$//
1772 ; # Clip off version number; we can use a newer version as well
1775 =item B<-hsc>, B<--hanging-side-comments>
1777 By default, perltidy tries to identify and align "hanging side
1778 comments", which are something like this:
1780 my $IGNORE = 0; # This is a side comment
1781 # This is a hanging side comment
1784 A comment is considered to be a hanging side comment if (1) it immediately
1785 follows a line with a side comment, or another hanging side comment, and
1786 (2) there is some leading whitespace on the line.
1787 To deactivate this feature, use B<-nhsc> or B<--nohanging-side-comments>.
1788 If block comments are preceded by a blank line, or have no leading
1789 whitespace, they will not be mistaken as hanging side comments.
1791 =item B<Closing Side Comments>
1793 A closing side comment is a special comment which perltidy can
1794 automatically create and place after the closing brace of a code block.
1795 They can be useful for code maintenance and debugging. The command
1796 B<-csc> (or B<--closing-side-comments>) adds or updates closing side
1797 comments. For example, here is a small code snippet
1800 if ( !defined( $_[0] ) ) {
1801 print("Hello, World\n");
1804 print( $_[0], "\n" );
1808 And here is the result of processing with C<perltidy -csc>:
1811 if ( !defined( $_[0] ) ) {
1812 print("Hello, World\n");
1815 print( $_[0], "\n" );
1817 } ## end sub message
1819 A closing side comment was added for C<sub message> in this case, but not
1820 for the C<if> and C<else> blocks, because they were below the 6 line
1821 cutoff limit for adding closing side comments. This limit may be
1822 changed with the B<-csci> command, described below.
1824 The command B<-dcsc> (or B<--delete-closing-side-comments>) reverses this
1825 process and removes these comments.
1827 Several commands are available to modify the behavior of these two basic
1828 commands, B<-csc> and B<-dcsc>:
1832 =item B<-csci=n>, or B<--closing-side-comment-interval=n>
1834 where C<n> is the minimum number of lines that a block must have in
1835 order for a closing side comment to be added. The default value is
1836 C<n=6>. To illustrate:
1838 # perltidy -csci=2 -csc
1840 if ( !defined( $_[0] ) ) {
1841 print("Hello, World\n");
1842 } ## end if ( !defined( $_[0] ))
1844 print( $_[0], "\n" );
1845 } ## end else [ if ( !defined( $_[0] ))
1846 } ## end sub message
1848 Now the C<if> and C<else> blocks are commented. However, now this has
1849 become very cluttered.
1851 =item B<-cscp=string>, or B<--closing-side-comment-prefix=string>
1853 where string is the prefix used before the name of the block type. The
1854 default prefix, shown above, is C<## end>. This string will be added to
1855 closing side comments, and it will also be used to recognize them in
1856 order to update, delete, and format them. Any comment identified as a
1857 closing side comment will be placed just a single space to the right of
1860 =item B<-cscl=string>, or B<--closing-side-comment-list>
1862 where C<string> is a list of block types to be tagged with closing side
1863 comments. By default, all code block types preceded by a keyword or
1864 label (such as C<if>, C<sub>, and so on) will be tagged. The B<-cscl>
1865 command changes the default list to be any selected block types; see
1866 L<"Specifying Block Types">.
1867 For example, the following command
1868 requests that only C<sub>'s, labels, C<BEGIN>, and C<END> blocks be
1869 affected by any B<-csc> or B<-dcsc> operation:
1871 -cscl="sub : BEGIN END"
1873 =item B<-csct=n>, or B<--closing-side-comment-maximum-text=n>
1875 The text appended to certain block types, such as an C<if> block, is
1876 whatever lies between the keyword introducing the block, such as C<if>,
1877 and the opening brace. Since this might be too much text for a side
1878 comment, there needs to be a limit, and that is the purpose of this
1879 parameter. The default value is C<n=20>, meaning that no additional
1880 tokens will be appended to this text after its length reaches 20
1881 characters. Omitted text is indicated with C<...>. (Tokens, including
1882 sub names, are never truncated, however, so actual lengths may exceed
1883 this). To illustrate, in the above example, the appended text of the
1884 first block is C< ( !defined( $_[0] )...>. The existing limit of
1885 C<n=20> caused this text to be truncated, as indicated by the C<...>. See
1886 the next flag for additional control of the abbreviated text.
1888 =item B<-cscb>, or B<--closing-side-comments-balanced>
1890 As discussed in the previous item, when the
1891 closing-side-comment-maximum-text limit is exceeded the comment text must
1892 be truncated. Older versions of perltidy terminated with three dots, and this
1893 can still be achieved with -ncscb:
1895 perltidy -csc -ncscb
1896 } ## end foreach my $foo (sort { $b cmp $a ...
1898 However this causes a problem with editors which cannot recognize
1899 comments or are not configured to do so because they cannot "bounce" around in
1900 the text correctly. The B<-cscb> flag has been added to
1901 help them by appending appropriate balancing structure:
1904 } ## end foreach my $foo (sort { $b cmp $a ... })
1906 The default is B<-cscb>.
1908 =item B<-csce=n>, or B<--closing-side-comment-else-flag=n>
1910 The default, B<n=0>, places the text of the opening C<if> statement after any
1913 If B<n=2> is used, then each C<elsif> is also given the text of the opening
1914 C<if> statement. Also, an C<else> will include the text of a preceding
1915 C<elsif> statement. Note that this may result some long closing
1918 If B<n=1> is used, the results will be the same as B<n=2> whenever the
1919 resulting line length is less than the maximum allowed.
1921 =item B<-cscb>, or B<--closing-side-comments-balanced>
1923 When using closing-side-comments, and the closing-side-comment-maximum-text
1924 limit is exceeded, then the comment text must be abbreviated.
1925 It is terminated with three dots if the B<-cscb> flag is negated:
1927 perltidy -csc -ncscb
1928 } ## end foreach my $foo (sort { $b cmp $a ...
1930 This causes a problem with older editors which do not recognize comments
1931 because they cannot "bounce" around in the text correctly. The B<-cscb>
1932 flag tries to help them by appending appropriate terminal balancing structures:
1935 } ## end foreach my $foo (sort { $b cmp $a ... })
1937 The default is B<-cscb>.
1940 =item B<-cscw>, or B<--closing-side-comment-warnings>
1942 This parameter is intended to help make the initial transition to the use of
1943 closing side comments.
1945 things to happen if a closing side comment replaces an existing, different
1946 closing side comment: first, an error message will be issued, and second, the
1947 original side comment will be placed alone on a new specially marked comment
1948 line for later attention.
1950 The intent is to avoid clobbering existing hand-written side comments
1951 which happen to match the pattern of closing side comments. This flag
1952 should only be needed on the first run with B<-csc>.
1956 B<Important Notes on Closing Side Comments:>
1962 Closing side comments are only placed on lines terminated with a closing
1963 brace. Certain closing styles, such as the use of cuddled elses
1964 (B<-ce>), preclude the generation of some closing side comments.
1968 Please note that adding or deleting of closing side comments takes
1969 place only through the commands B<-csc> or B<-dcsc>. The other commands,
1970 if used, merely modify the behavior of these two commands.
1974 It is recommended that the B<-cscw> flag be used along with B<-csc> on
1975 the first use of perltidy on a given file. This will prevent loss of
1976 any existing side comment data which happens to have the csc prefix.
1980 Once you use B<-csc>, you should continue to use it so that any
1981 closing side comments remain correct as code changes. Otherwise, these
1982 comments will become incorrect as the code is updated.
1986 If you edit the closing side comments generated by perltidy, you must also
1987 change the prefix to be different from the closing side comment prefix.
1988 Otherwise, your edits will be lost when you rerun perltidy with B<-csc>. For
1989 example, you could simply change C<## end> to be C<## End>, since the test is
1990 case sensitive. You may also want to use the B<-ssc> flag to keep these
1991 modified closing side comments spaced the same as actual closing side comments.
1995 Temporarily generating closing side comments is a useful technique for
1996 exploring and/or debugging a perl script, especially one written by someone
1997 else. You can always remove them with B<-dcsc>.
2001 =item B<Static Block Comments>
2003 Static block comments are block comments with a special leading pattern,
2004 C<##> by default, which will be treated slightly differently from other
2005 block comments. They effectively behave as if they had glue along their
2006 left and top edges, because they stick to the left edge and previous line
2007 when there is no blank spaces in those places. This option is
2008 particularly useful for controlling how commented code is displayed.
2012 =item B<-sbc>, B<--static-block-comments>
2014 When B<-sbc> is used, a block comment with a special leading pattern, C<##> by
2015 default, will be treated specially.
2017 Comments so identified are treated as follows:
2023 If there is no leading space on the line, then the comment will not
2024 be indented, and otherwise it may be,
2028 no new blank line will be
2029 inserted before such a comment, and
2033 such a comment will never become
2034 a hanging side comment.
2038 For example, assuming C<@month_of_year> is
2041 @month_of_year = ( # -sbc (default)
2042 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
2046 Without this convention, the above code would become
2048 @month_of_year = ( # -nsbc
2049 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
2055 which is not as clear.
2056 The default is to use B<-sbc>. This may be deactivated with B<-nsbc>.
2058 =item B<-sbcp=string>, B<--static-block-comment-prefix=string>
2060 This parameter defines the prefix used to identify static block comments
2061 when the B<-sbc> parameter is set. The default prefix is C<##>,
2062 corresponding to C<-sbcp=##>. The prefix is actually part of a perl
2063 pattern used to match lines and it must either begin with C<#> or C<^#>.
2064 In the first case a prefix ^\s* will be added to match any leading
2065 whitespace, while in the second case the pattern will match only
2066 comments with no leading whitespace. For example, to
2067 identify all comments as static block comments, one would use C<-sbcp=#>.
2068 To identify all left-adjusted comments as static block comments, use C<-sbcp='^#'>.
2070 Please note that B<-sbcp> merely defines the pattern used to identify static
2071 block comments; it will not be used unless the switch B<-sbc> is set. Also,
2072 please be aware that since this string is used in a perl regular expression
2073 which identifies these comments, it must enable a valid regular expression to
2076 A pattern which can be useful is:
2080 This pattern requires a static block comment to have at least one character
2081 which is neither a # nor a space. It allows a line containing only '#'
2082 characters to be rejected as a static block comment. Such lines are often used
2083 at the start and end of header information in subroutines and should not be
2084 separated from the intervening comments, which typically begin with just a
2087 =item B<-osbc>, B<--outdent-static-block-comments>
2089 The command B<-osbc> will cause static block comments to be outdented by 2
2090 spaces (or whatever B<-ci=n> has been set to), if possible.
2094 =item B<Static Side Comments>
2096 Static side comments are side comments with a special leading pattern.
2097 This option can be useful for controlling how commented code is displayed
2098 when it is a side comment.
2102 =item B<-ssc>, B<--static-side-comments>
2104 When B<-ssc> is used, a side comment with a static leading pattern, which is
2105 C<##> by default, will be spaced only a single space from previous
2106 character, and it will not be vertically aligned with other side comments.
2108 The default is B<-nssc>.
2110 =item B<-sscp=string>, B<--static-side-comment-prefix=string>
2112 This parameter defines the prefix used to identify static side comments
2113 when the B<-ssc> parameter is set. The default prefix is C<##>,
2114 corresponding to C<-sscp=##>.
2116 Please note that B<-sscp> merely defines the pattern used to identify
2117 static side comments; it will not be used unless the switch B<-ssc> is
2118 set. Also, note that this string is used in a perl regular expression
2119 which identifies these comments, so it must enable a valid regular
2120 expression to be formed.
2126 =head2 Skipping Selected Sections of Code
2128 Selected lines of code may be passed verbatim to the output without any
2129 formatting by marking the starting and ending lines with special comments.
2130 There are two options for doing this. The first option is called
2131 B<--format-skipping> or B<-fs>, and the second option is called
2132 B<--code-skipping> or B<-cs>.
2134 In both cases the lines of code will be output without any changes.
2135 The difference is that in B<--format-skipping>
2136 perltidy will still parse the marked lines of code and check for errors,
2137 whereas in B<--code-skipping> perltidy will simply pass the lines to the output without any checking.
2139 Both of these features are enabled by default and are invoked with special
2140 comment markers. B<--format-skipping> uses starting and ending markers '#<<<'
2141 and '#>>>', like this:
2143 #<<< format skipping: do not let perltidy change my nice formatting
2151 B<--code-skipping> uses starting and ending markers '#<<V' and '#>>V', like
2154 #<<V code skipping: perltidy will pass this verbatim without error checking
2157 [ [ <?word> | _ | <?digit> ] <?ident_digit>
2164 Additional text may appear on the special comment lines provided that it
2165 is separated from the marker by at least one space, as in the above examples.
2167 Any number of code-skipping or format-skipping sections may appear in a file.
2168 If an opening code-skipping or format-skipping comment is not followed by a
2169 corresponding closing comment, then skipping continues to the end of the file.
2170 If a closing code-skipping or format-skipping comment appears in a file but
2171 does not follow a corresponding opening comment, then it is treated as an
2172 ordinary comment without any special meaning.
2174 It is recommended to use B<--code-skipping> only if you need to hide a block of
2175 an extended syntax which would produce errors if parsed by perltidy, and use
2176 B<--format-skipping> otherwise. This is because the B<--format-skipping>
2177 option provides the benefits of error checking, and there are essentially no
2178 limitations on which lines to which it can be applied. The B<--code-skipping>
2179 option, on the other hand, does not do error checking and its use is more
2180 restrictive because the code which remains, after skipping the marked lines,
2181 must be syntactically correct code with balanced containers.
2183 These features should be used sparingly to avoid littering code with markers,
2184 but they can be helpful for working around occasional problems.
2186 Note that it may be possible to avoid the use of B<--format-skipping> for the
2187 specific case of a comma-separated list of values, as in the above example, by
2188 simply inserting a blank or comment somewhere between the opening and closing
2189 parens. See the section L<"Controlling List Formatting">.
2191 The following sections describe the available controls for these options. They
2192 should not normally be needed.
2196 =item B<-fs>, B<--format-skipping>
2198 As explained above, this flag, which is enabled by default, causes any code
2199 between special beginning and ending comment markers to be passed to the output
2200 without formatting. The code between the comments is still checked for errors
2201 however. The default beginning marker is #<<< and the default ending marker is
2204 Format skipping begins when a format skipping beginning comment is seen and
2205 continues until a format-skipping ending comment is found.
2207 This feature can be disabled with B<-nfs>. This should not normally be necessary.
2209 =item B<-fsb=string>, B<--format-skipping-begin=string>
2211 This and the next parameter allow the special beginning and ending comments to
2212 be changed. However, it is recommended that they only be changed if there is a
2213 conflict between the default values and some other use. If they are used, it
2214 is recommended that they only be entered in a B<.perltidyrc> file, rather than
2215 on a command line. This is because properly escaping these parameters on a
2216 command line can be difficult.
2218 If changed comment markers do not appear to be working, use the B<-log> flag and
2219 examine the F<.LOG> file to see if and where they are being detected.
2221 The B<-fsb=string> parameter may be used to change the beginning marker for
2222 format skipping. The default is equivalent to -fsb='#<<<'. The string that
2223 you enter must begin with a # and should be in quotes as necessary to get past
2224 the command shell of your system. It is actually the leading text of a pattern
2225 that is constructed by appending a '\s', so you must also include backslashes
2226 for characters to be taken literally rather than as patterns.
2228 Some examples show how example strings become patterns:
2230 -fsb='#\{\{\{' becomes /^#\{\{\{\s/ which matches #{{{ but not #{{{{
2231 -fsb='#\*\*' becomes /^#\*\*\s/ which matches #** but not #***
2232 -fsb='#\*{2,}' becomes /^#\*{2,}\s/ which matches #** and #*****
2234 =item B<-fse=string>, B<--format-skipping-end=string>
2236 The B<-fse=string> is the corresponding parameter used to change the
2237 ending marker for format skipping. The default is equivalent to
2240 The beginning and ending strings may be the same, but it is preferable
2241 to make them different for clarity.
2243 =item B<-cs>, B<--code-skipping>
2245 As explained above, this flag, which is enabled by default, causes any code
2246 between special beginning and ending comment markers to be directly passed to
2247 the output without any error checking or formatting. Essentially, perltidy
2248 treats it as if it were a block of arbitrary text. The default beginning
2249 marker is #<<V and the default ending marker is #>>V.
2251 This feature can be disabled with B<-ncs>. This should not normally be
2254 =item B<-csb=string>, B<--code-skipping-begin=string>
2256 This may be used to change the beginning comment for a B<--code-skipping> section, and its use is similar to the B<-fsb=string>.
2257 The default is equivalent to -csb='#<<V'.
2259 =item B<-cse=string>, B<--code-skipping-end=string>
2261 This may be used to change the ending comment for a B<--code-skipping> section, and its use is similar to the B<-fse=string>.
2262 The default is equivalent to -cse='#>>V'.
2266 =head2 Line Break Control
2268 The parameters in this and the next sections control breaks after
2269 non-blank lines of code. Blank lines are controlled
2270 separately by parameters in the section L<"Blank Line Control">.
2274 =item B<-dnl>, B<--delete-old-newlines>
2276 By default, perltidy first deletes all old line break locations, and then it
2277 looks for good break points to match the desired line length. Use B<-ndnl>
2278 or B<--nodelete-old-newlines> to force perltidy to retain all old line break
2281 =item B<-anl>, B<--add-newlines>
2283 By default, perltidy will add line breaks when necessary to create
2284 continuations of long lines and to improve the script appearance. Use
2285 B<-nanl> or B<--noadd-newlines> to prevent any new line breaks.
2287 This flag does not prevent perltidy from eliminating existing line
2288 breaks; see B<--freeze-newlines> to completely prevent changes to line
2291 =item B<-fnl>, B<--freeze-newlines>
2293 If you do not want any changes to the line breaks within
2294 lines of code in your script, set
2295 B<-fnl>, and they will remain fixed, and the rest of the commands in
2296 this section and sections
2297 L<"Controlling List Formatting">,
2298 L<"Retaining or Ignoring Existing Line Breaks">.
2299 You may want to use B<-noll> with this.
2301 Note: If you also want to keep your blank lines exactly
2302 as they are, you can use the B<-fbl> flag which is described
2303 in the section L<"Blank Line Control">.
2307 =head2 Controlling Breaks at Braces, Parens, and Square Brackets
2311 =item B<-ce>, B<--cuddled-else>
2313 Enable the "cuddled else" style, in which C<else> and C<elsif> are
2314 follow immediately after the curly brace closing the previous block.
2315 The default is not to use cuddled elses, and is indicated with the flag
2316 B<-nce> or B<--nocuddled-else>. Here is a comparison of the
2334 In this example the keyword B<else> is placed on the same line which begins with
2335 the preceding closing block brace and is followed by its own opening block brace
2336 on the same line. Other keywords and function names which are formatted with
2337 this "cuddled" style are B<elsif>, B<continue>, B<catch>, B<finally>.
2339 Other block types can be formatted by specifying their names on a
2340 separate parameter B<-cbl>, described in a later section.
2342 Cuddling between a pair of code blocks requires that the closing brace of the
2343 first block start a new line. If this block is entirely on one line in the
2344 input file, it is necessary to decide if it should be broken to allow cuddling.
2345 This decision is controlled by the flag B<-cbo=n> discussed below. The default
2346 and recommended value of B<-cbo=1> bases this decision on the first block in
2347 the chain. If it spans multiple lines then cuddling is made and continues
2348 along the chain, regardless of the sizes of subsequent blocks. Otherwise, short
2349 lines remain intact.
2351 So for example, the B<-ce> flag would not have any effect if the above snippet
2354 if ($task) { yyy() }
2357 If the first block spans multiple lines, then cuddling can be done and will
2358 continue for the subsequent blocks in the chain, as illustrated in the previous
2361 If there are blank lines between cuddled blocks they will be eliminated. If
2362 there are comments after the closing brace where cuddling would occur then
2363 cuddling will be prevented. If this occurs, cuddling will restart later in the
2366 =item B<-cb>, B<--cuddled-blocks>
2368 This flag is equivalent to B<-ce>.
2371 =item B<-cbl>, B<--cuddled-block-list>
2373 The built-in default cuddled block types are B<else, elsif, continue, catch, finally>.
2375 Additional block types to which the B<-cuddled-blocks> style applies can be defined by
2376 this parameter. This parameter is a character string, giving a list of
2377 block types separated by commas or spaces. For example, to cuddle code blocks
2378 of type sort, map and grep, in addition to the default types, the string could
2381 -cbl="sort map grep"
2387 Note however that these particular block types are typically short so there might not be much
2388 opportunity for the cuddled format style.
2390 Using commas avoids the need to protect spaces with quotes.
2392 As a diagnostic check, the flag B<--dump-cuddled-block-list> or B<-dcbl> can be
2393 used to view the hash of values that are generated by this flag.
2395 Finally, note that the B<-cbl> flag by itself merely specifies which blocks are formatted
2396 with the cuddled format. It has no effect unless this formatting style is activated with
2399 =item B<-cblx>, B<--cuddled-block-list-exclusive>
2401 When cuddled else formatting is selected with B<-ce>, setting this flag causes
2402 perltidy to ignore its built-in defaults and rely exclusively on the block types
2403 specified on the B<-cbl> flag described in the previous section. For example,
2404 to avoid using cuddled B<catch> and B<finally>, which are among the defaults, the
2405 following set of parameters could be used:
2407 perltidy -ce -cbl='else elsif continue' -cblx
2410 =item B<-cbo=n>, B<--cuddled-break-option=n>
2412 Cuddled formatting is only possible between a pair of code blocks if the
2413 closing brace of the first block starts a new line. If a block is encountered
2414 which is entirely on a single line, and cuddled formatting is selected, it is
2415 necessary to make a decision as to whether or not to "break" the block, meaning
2416 to cause it to span multiple lines. This parameter controls that decision. The
2419 cbo=0 Never force a short block to break.
2420 cbo=1 If the first of a pair of blocks is broken in the input file,
2421 then break the second [DEFAULT].
2422 cbo=2 Break open all blocks for maximal cuddled formatting.
2424 The default and recommended value is B<cbo=1>. With this value, if the starting
2425 block of a chain spans multiple lines, then a cascade of breaks will occur for
2426 remaining blocks causing the entire chain to be cuddled.
2428 The option B<cbo=0> can produce erratic cuddling if there are numerous one-line
2431 The option B<cbo=2> produces maximal cuddling but will not allow any short blocks.
2434 =item B<-bl>, B<--opening-brace-on-new-line>, or B<--brace-left>
2436 Use the flag B<-bl> to place an opening block brace on a new line:
2438 if ( $input_file eq '-' )
2443 By default it applies to all structural blocks except B<sort map grep eval> and
2446 The default is B<-nbl> which places an opening brace on the same line as
2447 the keyword introducing it if possible. For example,
2450 if ( $input_file eq '-' ) {
2454 When B<-bl> is set, the blocks to which this applies can be controlled with the
2455 parameters B<--brace-left-list> and B<-brace-left-exclusion-list> described in the next sections.
2457 =item B<-bll=s>, B<--brace-left-list=s>
2459 Use this parameter to change the types of block braces for which the
2460 B<-bl> flag applies; see L<"Specifying Block Types">. For example,
2461 B<-bll='if elsif else sub'> would apply it to only C<if/elsif/else>
2462 and named sub blocks. The default is all blocks, B<-bll='*'>.
2464 =item B<-blxl=s>, B<--brace-left-exclusion-list=s>
2466 Use this parameter to exclude types of block braces for which the
2467 B<-bl> flag applies; see L<"Specifying Block Types">. For example,
2468 the default settings B<-bll='*'> and B<-blxl='sort map grep eval asub'>
2469 mean all blocks except B<sort map grep eval> and anonymous sub blocks.
2471 Note that the lists B<-bll=s> and B<-blxl=s> control the behavior of the
2472 B<-bl> flag but have no effect unless the B<-bl> flag is set.
2474 =item B<-sbl>, B<--opening-sub-brace-on-new-line>
2476 The flag B<-sbl> provides a shortcut way to turn on B<-bl> just for named
2477 subs. The same effect can be achieved by turning on B<-bl>
2478 with the block list set as B<-bll='sub'>.
2484 produces this result:
2488 if (!defined($_[0])) {
2489 print("Hello, World\n");
2496 This flag is negated with B<-nsbl>, which is the default.
2498 =item B<-asbl>, B<--opening-anonymous-sub-brace-on-new-line>
2500 The flag B<-asbl> is like the B<-sbl> flag except that it applies
2501 to anonymous sub's instead of named subs. For example
2505 produces this result:
2509 if ( !defined( $_[0] ) ) {
2510 print("Hello, World\n");
2513 print( $_[0], "\n" );
2517 This flag is negated with B<-nasbl>, and the default is B<-nasbl>.
2519 =item B<-bli>, B<--brace-left-and-indent>
2521 The flag B<-bli> is similar to the B<-bl> flag but in addition it causes one
2522 unit of continuation indentation ( see B<-ci> ) to be placed before
2523 an opening and closing block braces.
2525 For example, perltidy -bli gives
2527 if ( $input_file eq '-' )
2529 important_function();
2532 By default, this extra indentation occurs for block types:
2533 B<if>, B<elsif>, B<else>, B<unless>, B<while>, B<for>, B<foreach>, B<do>, and
2534 also B<named subs> and blocks preceded by a B<label>. The next item shows how to
2537 B<Note>: The B<-bli> flag is similar to the B<-bl> flag, with the difference being
2538 that braces get indented. But these two flags are implemented independently,
2539 and have different default settings for historical reasons. If desired, a
2540 mixture of effects can be achieved if desired by turning them both on with
2541 different B<-list> settings. In the event that both settings are selected for
2542 a certain block type, the B<-bli> style has priority.
2544 =item B<-blil=s>, B<--brace-left-and-indent-list=s>
2546 Use this parameter to change the types of block braces for which the
2547 B<-bli> flag applies; see L<"Specifying Block Types">.
2549 The default is B<-blil='if else elsif unless while for foreach do : sub'>.
2551 =item B<-blixl=s>, B<--brace-left-and-indent-exclusion-list=s>
2553 Use this parameter to exclude types of block braces for which the B<-bli> flag
2554 applies; see L<"Specifying Block Types">.
2556 This might be useful in conjunction with selecting all blocks B<-blil='*'>.
2557 The default setting is B<-blixl=' '>, which does not exclude any blocks.
2559 Note that the two parameters B<-blil> and B<-blixl> control the behavior of
2560 the B<-bli> flag but have no effect unless the B<-bli> flag is set.
2562 =item B<-bar>, B<--opening-brace-always-on-right>
2564 The default style, B<-nbl> places the opening code block brace on a new
2565 line if it does not fit on the same line as the opening keyword, like
2568 if ( $bigwasteofspace1 && $bigwasteofspace2
2569 || $bigwasteofspace3 && $bigwasteofspace4 )
2571 big_waste_of_time();
2574 To force the opening brace to always be on the right, use the B<-bar>
2575 flag. In this case, the above example becomes
2577 if ( $bigwasteofspace1 && $bigwasteofspace2
2578 || $bigwasteofspace3 && $bigwasteofspace4 ) {
2579 big_waste_of_time();
2582 A conflict occurs if both B<-bl> and B<-bar> are specified.
2584 =item B<-otr>, B<--opening-token-right> and related flags
2586 The B<-otr> flag is a hint that perltidy should not place a break between a
2587 comma and an opening token. For example:
2589 # default formatting
2590 push @{ $self->{$module}{$key} },
2592 accno => $ref->{accno},
2593 description => $ref->{description}
2597 push @{ $self->{$module}{$key} }, {
2598 accno => $ref->{accno},
2599 description => $ref->{description}
2602 The flag B<-otr> is actually an abbreviation for three other flags
2603 which can be used to control parens, hash braces, and square brackets
2604 separately if desired:
2606 -opr or --opening-paren-right
2607 -ohbr or --opening-hash-brace-right
2608 -osbr or --opening-square-bracket-right
2610 =item B<-bbhb=n>, B<--break-before-hash-brace=n> and related flags
2612 When a list of items spans multiple lines, the default formatting is to place
2613 the opening brace (or other container token) at the end of the starting line,
2623 This flag can change the default behavior to cause a line break to be placed
2624 before the opening brace according to the value given to the integer B<n>:
2626 -bbhb=0 never break [default]
2627 -bbhb=1 stable: break if the input script had a break
2628 -bbhb=2 break if list is 'complex' (see note below)
2629 -bbhb=3 always break
2642 There are several points to note about this flag:
2648 This parameter only applies if the opening brace is preceded by an '='
2653 This parameter only applies if the contents of the container looks like a list.
2654 The contents need to contain some commas or '=>'s at the next interior level to
2655 be considered a list.
2659 For the B<n=2> option, a list is considered 'complex' if it is part of a nested list
2660 structure which spans multiple lines in the input file.
2664 If multiple opening tokens have been 'welded' together with the B<-wn> parameter, then
2665 this parameter has no effect.
2669 The indentation of the braces will normally be one level of continuation
2670 indentation by default. This can be changed with the parameter
2671 B<-bbhbi=n> in the next section.
2675 Similar flags for controlling parens and square brackets are given in the subsequent section.
2679 =item B<-bbhbi=n>, B<--break-before-hash-brace-and-indent=n>
2681 This flag is a companion to B<-bbhb=n> for controlling the indentation of an opening hash brace
2682 which is placed on a new line by that parameter. The indentation is as follows:
2684 -bbhbi=0 one continuation level [default]
2685 -bbhbi=1 outdent by one continuation level
2686 -bbhbi=2 indent one full indentation level
2690 # perltidy -bbhb=3 -bbhbi=1
2699 # perltidy -bbhb=3 -bbhbi=2
2708 Note that this parameter has no effect unless B<-bbhb=n> is also set.
2710 =item B<-bbsb=n>, B<--break-before-square-bracket=n>
2712 This flag is similar to the flag described above, except it applies to lists contained within square brackets.
2714 -bbsb=0 never break [default]
2715 -bbsb=1 stable: break if the input script had a break
2716 -bbsb=2 break if list is 'complex' (part of nested list structure)
2717 -bbsb=3 always break
2719 =item B<-bbsbi=n>, B<--break-before-square-bracket-and-indent=n>
2721 This flag is a companion to B<-bbsb=n> for controlling the indentation of an opening square bracket
2722 which is placed on a new line by that parameter. The indentation is as follows:
2724 -bbsbi=0 one continuation level [default]
2725 -bbsbi=1 outdent by one continuation level
2726 -bbsbi=2 indent one full indentation level
2728 =item B<-bbp=n>, B<--break-before-paren=n>
2730 This flag is similar to B<-bbhb=n>, described above, except it applies to lists contained within parens.
2732 -bbp=0 never break [default]
2733 -bbp=1 stable: break if the input script had a break
2734 -bpb=2 break if list is 'complex' (part of nested list structure)
2737 =item B<-bbpi=n>, B<--break-before-paren-and-indent=n>
2739 This flag is a companion to B<-bbp=n> for controlling the indentation of an opening paren
2740 which is placed on a new line by that parameter. The indentation is as follows:
2742 -bbpi=0 one continuation level [default]
2743 -bbpi=1 outdent by one continuation level
2744 -bbpi=2 indent one full indentation level
2752 =item B<-wn>, B<--weld-nested-containers>
2754 The B<-wn> flag causes closely nested pairs of opening and closing container
2755 symbols (curly braces, brackets, or parens) to be "welded" together, meaning
2756 that they are treated as if combined into a single unit, with the indentation
2757 of the innermost code reduced to be as if there were just a single container
2762 # default formatting
2772 } } until $x++ > $z;
2774 When this flag is set perltidy makes a preliminary pass through the file and
2775 identifies all nested pairs of containers. To qualify as a nested pair, the
2776 closing container symbols must be immediately adjacent and the opening symbols
2777 must either (1) be adjacent as in the above example, or (2) have an anonymous
2778 sub declaration following an outer opening container symbol which is not a
2779 code block brace, or (3) have an outer opening paren separated from the inner
2780 opening symbol by any single non-container symbol or something that looks like
2781 a function evaluation, as illustrated in the next examples. An additonal
2782 option (4) which can be turned on with the flag B<--weld-fat-comma> is when the opening container symbols are separated by a hash key and fat comma (=>).
2784 Any container symbol may serve as both the inner container of one pair and as
2785 the outer container of an adjacent pair. Consequently, any number of adjacent
2786 opening or closing symbols may join together in weld. For example, here are
2787 three levels of wrapped function calls:
2789 # default formatting
2790 my (@date_time) = Localtime(
2793 $year, $month, $day, $hour, $minute, $second,
2794 '0', $offset, '0', '0'
2800 my (@date_time) = Localtime( Date_to_Time( Add_Delta_DHMS(
2801 $year, $month, $day, $hour, $minute, $second,
2802 '0', $offset, '0', '0'
2805 Notice how the indentation of the inner lines are reduced by two levels in this
2806 case. This example also shows the typical result of this formatting, namely it
2807 is a sandwich consisting of an initial opening layer, a central section of any
2808 complexity forming the "meat" of the sandwich, and a final closing layer. This
2809 predictable structure helps keep the compacted structure readable.
2811 The inner sandwich layer is required to be at least one line thick. If this
2812 cannot be achieved, welding does not occur. This constraint can cause
2813 formatting to take a couple of iterations to stabilize when it is first applied
2814 to a script. The B<-conv> flag can be used to insure that the final format is
2815 achieved in a single run.
2817 Here is an example illustrating a welded container within a welded containers:
2819 # default formatting
2824 $sx * int( $xr->numify() ) & $sy * int( $yr->numify() )
2834 $sx * int( $xr->numify() ) & $sy * int( $yr->numify() )
2839 The welded closing tokens are by default on a separate line but this can be
2840 modified with the B<-vtc=n> flag (described in the next section). For example,
2841 the same example adding B<-vtc=2> is
2843 # perltidy -wn -vtc=2
2846 $sx * int( $xr->numify() ) & $sy * int( $yr->numify() ) ) ),
2849 This format option is quite general but there are some limitations.
2851 One limitation is that any line length limit still applies and can cause long
2852 welded sections to be broken into multiple lines.
2854 Another limitation is that an opening symbol which delimits quoted text cannot
2855 be included in a welded pair. This is because quote delimiters are treated
2856 specially in perltidy.
2858 Finally, the stacking of containers defined by this flag have priority over
2859 any other container stacking flags. This is because any welding is done first.
2861 =item B<-wfc>, B<--weld-fat-comma >
2863 When the B<-wfc> flag is set, along with B<-wn>, perltidy is allowed to weld
2864 an opening paren to an inner opening container when they are separated by a hash key and fat comma (=>). for example
2867 elf->call_method( method_name_foo => {
2869 some_other_arg3 => $bar->{'baz'},
2872 This option is off by default.
2874 =item B<-wnxl=s>, B<--weld-nested-exclusion-list>
2876 The B<-wnxl=s> flag provides some control over the types of containers which
2877 can be welded. The B<-wn> flag by default is "greedy" in welding adjacent
2878 containers. If it welds more types of containers than desired, this flag
2879 provides a capability to reduce the amount of welding by specifying a list
2880 of things which should B<not> be welded.
2882 The logic in perltidy to apply this is straightforward. As each container
2883 token is being considered for joining a weld, any exclusion rules are consulted
2884 and used to reject the weld if necessary.
2886 This list is a string with space-separated items. Each item consists of up to
2887 three pieces of information: (1) an optional position, (2) an optional
2888 preceding type, and (3) a container type.
2890 The only required piece of information is a container type, which is one of
2891 '(', '[', '{' or 'q'. The first three of these are container tokens and the
2892 last represents a quoted list. For example the string
2896 means do B<NOT> include square-bracets, braces, or quotes in any welds. The only unspecified
2897 container is '(', so this string means that only welds involving parens will be made.
2899 To illustrate, following welded snippet consists of a chain of three welded
2900 containers with types '(' '[' and 'q':
2910 Even though the qw term uses parens as the quote delimiter, it has a special
2911 type 'q' here. If it appears in a weld it always appears at the end of the
2914 Any of the container types '[', '{', and '(' may be prefixed with a position
2915 indicator which is either '^', to indicate the first token of a welded
2916 sequence, or '.', to indicate an interior token of a welded sequence. (Since
2917 a quoted string 'q' always ends a chain it does need a position indicator).
2919 For example, if we do not want a sequence of welded containers to start with a
2920 square bracket we could use
2924 In the above snippet, there is a square bracket but it does not start the chain,
2925 so the formatting would be unchanged if it were formatted with this restriction.
2927 A third optional item of information which can be given is an alphanumeric
2928 letter which is used to limit the selection further depending on the type of
2929 token immediately before the container. If given, it goes just before the
2930 container symbol. The possible letters are currently 'k', 'K', 'f', 'F',
2931 'w', and 'W', with these meanings:
2933 'k' matches if the previous nonblank token is a perl built-in keyword (such as 'if', 'while'),
2934 'K' matches if 'k' does not, meaning that the previous token is not a keyword.
2935 'f' matches if the previous token is a function other than a keyword.
2936 'F' matches if 'f' does not.
2937 'w' matches if either 'k' or 'f' match.
2938 'W' matches if 'w' does not.
2940 For example, compare
2943 if ( defined( $_Cgi_Query{
2944 $Config{'methods'}{'authentication'}{'remote'}{'cgi'}{'username'}
2949 # perltidy -wn -wnxl='^K( {'
2951 $_Cgi_Query{ $Config{'methods'}{'authentication'}{'remote'}{'cgi'}
2955 The first case does maximum welding. In the second case the leading paren is
2956 retained by the rule (it would have been rejected if preceded by a non-keyword)
2957 but the curly brace is rejected by the rule.
2959 Here are some additional example strings and their meanings:
2961 '^(' - the weld must not start with a paren
2962 '.(' - the second and later tokens may not be parens
2963 '.w(' - the second and later tokens may not keyword or function call parens
2964 '(' - no parens in a weld
2965 '^K(' - exclude a leading paren preceded by a non-keyword
2966 '.k(' - exclude a secondary paren preceded by a keyword
2967 '[ {' - exclude all brackets and braces
2968 '[ ( ^K{' - exclude everything except nested structures like do {{ ... }}
2971 =item B<Vertical tightness> of non-block curly braces, parentheses, and square brackets.
2973 These parameters control what shall be called vertical tightness. Here are the
2980 Opening tokens (except for block braces) are controlled by B<-vt=n>, or
2981 B<--vertical-tightness=n>, where
2983 -vt=0 always break a line after opening token (default).
2984 -vt=1 do not break unless this would produce more than one
2985 step in indentation in a line.
2986 -vt=2 never break a line after opening token
2990 You must also use the B<-lp> flag when you use the B<-vt> flag; the
2991 reason is explained below.
2995 Closing tokens (except for block braces) are controlled by B<-vtc=n>, or
2996 B<--vertical-tightness-closing=n>, where
2998 -vtc=0 always break a line before a closing token (default),
2999 -vtc=1 do not break before a closing token which is followed
3000 by a semicolon or another closing token, and is not in
3002 -vtc=2 never break before a closing token.
3003 -vtc=3 Like -vtc=1 except always break before a closing token
3004 if the corresponding opening token follows an = or =>.
3006 The rules for B<-vtc=1> and B<-vtc=3> are designed to maintain a reasonable
3007 balance between tightness and readability in complex lists.
3011 Different controls may be applied to different token types,
3012 and it is also possible to control block braces; see below.
3016 Finally, please note that these vertical tightness flags are merely
3017 hints to the formatter, and it cannot always follow them. Things which
3018 make it difficult or impossible include comments, blank lines, blocks of
3019 code within a list, and possibly the lack of the B<-lp> parameter.
3020 Also, these flags may be ignored for very small lists (2 or 3 lines in
3025 Here are some examples:
3027 # perltidy -lp -vt=0 -vtc=0
3035 # perltidy -lp -vt=1 -vtc=0
3036 %romanNumerals = ( one => 'I',
3042 # perltidy -lp -vt=1 -vtc=1
3043 %romanNumerals = ( one => 'I',
3063 In the last example for B<-vtc=3>, the opening paren is preceded by an equals
3064 so the closing paren is placed on a new line.
3066 The difference between B<-vt=1> and B<-vt=2> is shown here:
3068 # perltidy -lp -vt=1
3070 mysprintf( "(void)find_threadsv(%s);",
3071 cstring( $threadsv_names[ $op->targ ] )
3075 # perltidy -lp -vt=2
3076 $init->add( mysprintf( "(void)find_threadsv(%s);",
3077 cstring( $threadsv_names[ $op->targ ] )
3081 With B<-vt=1>, the line ending in C<add(> does not combine with the next
3082 line because the next line is not balanced. This can help with
3083 readability, but B<-vt=2> can be used to ignore this rule.
3085 The tightest, and least readable, code is produced with both C<-vt=2> and
3088 # perltidy -lp -vt=2 -vtc=2
3089 $init->add( mysprintf( "(void)find_threadsv(%s);",
3090 cstring( $threadsv_names[ $op->targ ] ) ) );
3092 Notice how the code in all of these examples collapses vertically as
3093 B<-vt> increases, but the indentation remains unchanged. This is
3094 because perltidy implements the B<-vt> parameter by first formatting as
3095 if B<-vt=0>, and then simply overwriting one output line on top of the
3096 next, if possible, to achieve the desired vertical tightness. The
3097 B<-lp> indentation style has been designed to allow this vertical
3098 collapse to occur, which is why it is required for the B<-vt> parameter.
3100 The B<-vt=n> and B<-vtc=n> parameters apply to each type of container
3101 token. If desired, vertical tightness controls can be applied
3102 independently to each of the closing container token types.
3104 The parameters for controlling parentheses are B<-pvt=n> or
3105 B<--paren-vertical-tightness=n>, and B<-pvtc=n> or
3106 B<--paren-vertical-tightness-closing=n>.
3108 Likewise, the parameters for square brackets are B<-sbvt=n> or
3109 B<--square-bracket-vertical-tightness=n>, and B<-sbvtc=n> or
3110 B<--square-bracket-vertical-tightness-closing=n>.
3112 Finally, the parameters for controlling non-code block braces are
3113 B<-bvt=n> or B<--brace-vertical-tightness=n>, and B<-bvtc=n> or
3114 B<--brace-vertical-tightness-closing=n>.
3116 In fact, the parameter B<-vt=n> is actually just an abbreviation for
3117 B<-pvt=n -bvt=n sbvt=n>, and likewise B<-vtc=n> is an abbreviation
3118 for B<-pvtc=n -bvtc=n -sbvtc=n>.
3120 =item B<-bbvt=n> or B<--block-brace-vertical-tightness=n>
3122 The B<-bbvt=n> flag is just like the B<-vt=n> flag but applies
3123 to opening code block braces.
3125 -bbvt=0 break after opening block brace (default).
3126 -bbvt=1 do not break unless this would produce more than one
3127 step in indentation in a line.
3128 -bbvt=2 do not break after opening block brace.
3130 It is necessary to also use either B<-bl> or B<-bli> for this to work,
3131 because, as with other vertical tightness controls, it is implemented by
3132 simply overwriting a line ending with an opening block brace with the
3133 subsequent line. For example:
3135 # perltidy -bli -bbvt=0
3136 if ( open( FILE, "< $File" ) )
3138 while ( $File = <FILE> )
3146 # perltidy -bli -bbvt=1
3147 if ( open( FILE, "< $File" ) )
3148 { while ( $File = <FILE> )
3155 By default this applies to blocks associated with keywords B<if>,
3156 B<elsif>, B<else>, B<unless>, B<for>, B<foreach>, B<sub>, B<while>,
3157 B<until>, and also with a preceding label. This can be changed with
3158 the parameter B<-bbvtl=string>, or
3159 B<--block-brace-vertical-tightness-list=string>, where B<string> is a
3160 space-separated list of block types. For more information on the
3161 possible values of this string, see L<"Specifying Block Types">
3163 For example, if we want to just apply this style to C<if>,
3164 C<elsif>, and C<else> blocks, we could use
3165 C<perltidy -bli -bbvt=1 -bbvtl='if elsif else'>.
3167 There is no vertical tightness control for closing block braces; with
3168 one exception they will be placed on separate lines.
3169 The exception is that a cascade of closing block braces may
3170 be stacked on a single line. See B<-scbb>.
3172 =item B<-sot>, B<--stack-opening-tokens> and related flags
3174 The B<-sot> flag tells perltidy to "stack" opening tokens
3175 when possible to avoid lines with isolated opening tokens.
3180 $opt_c = Text::CSV_XS->new(
3189 $opt_c = Text::CSV_XS->new( {
3196 For detailed control of individual closing tokens the following
3197 controls can be used:
3199 -sop or --stack-opening-paren
3200 -sohb or --stack-opening-hash-brace
3201 -sosb or --stack-opening-square-bracket
3202 -sobb or --stack-opening-block-brace
3204 The flag B<-sot> is an abbreviation for B<-sop -sohb -sosb>.
3206 The flag B<-sobb> is an abbreviation for B<-bbvt=2 -bbvtl='*'>. This
3207 will case a cascade of opening block braces to appear on a single line,
3208 although this an uncommon occurrence except in test scripts.
3210 =item B<-sct>, B<--stack-closing-tokens> and related flags
3212 The B<-sct> flag tells perltidy to "stack" closing tokens
3213 when possible to avoid lines with isolated closing tokens.
3218 $opt_c = Text::CSV_XS->new(
3227 $opt_c = Text::CSV_XS->new(
3234 The B<-sct> flag is somewhat similar to the B<-vtc> flags, and in some
3235 cases it can give a similar result. The difference is that the B<-vtc>
3236 flags try to avoid lines with leading opening tokens by "hiding" them at
3237 the end of a previous line, whereas the B<-sct> flag merely tries to
3238 reduce the number of lines with isolated closing tokens by stacking them
3239 but does not try to hide them. For example:
3242 $opt_c = Text::CSV_XS->new(
3246 always_quote => 1, } );
3248 For detailed control of the stacking of individual closing tokens the
3249 following controls can be used:
3251 -scp or --stack-closing-paren
3252 -schb or --stack-closing-hash-brace
3253 -scsb or --stack-closing-square-bracket
3254 -scbb or --stack-closing-block-brace
3256 The flag B<-sct> is an abbreviation for stacking the non-block closing
3257 tokens, B<-scp -schb -scsb>.
3259 Stacking of closing block braces, B<-scbb>, causes a cascade of isolated
3260 closing block braces to be combined into a single line as in the following
3268 push( @lines, "$w1 $w2 $w3 $w4\n" );
3271 To simplify input even further for the case in which both opening and closing
3272 non-block containers are stacked, the flag B<-sac> or B<--stack-all-containers>
3273 is an abbreviation for B<-sot -sct>.
3275 Please note that if both opening and closing tokens are to be stacked, then the
3276 newer flag B<-weld-nested-containers> may be preferable because it insures that
3277 stacking is always done symmetrically. It also removes an extra level of
3278 unnecessary indentation within welded containers. It is able to do this
3279 because it works on formatting globally rather than locally, as the B<-sot> and
3284 =head2 Breaking Before or After Operators
3286 Four command line parameters provide some control over whether
3287 a line break should be before or after specific token types.
3288 Two parameters give detailed control:
3290 B<-wba=s> or B<--want-break-after=s>, and
3292 B<-wbb=s> or B<--want-break-before=s>.
3294 These parameters are each followed by a quoted string, B<s>, containing
3295 a list of token types (separated only by spaces). No more than one of each
3296 of these parameters should be specified, because repeating a
3297 command-line parameter always overwrites the previous one before
3298 perltidy ever sees it.
3300 By default, perltidy breaks B<after> these token types:
3301 % + - * / x != == >= <= =~ !~ < > | &
3302 = **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x=
3304 And perltidy breaks B<before> these token types by default:
3307 To illustrate, to cause a break after a concatenation operator, C<'.'>,
3308 rather than before it, the command line would be
3312 As another example, the following command would cause a break before
3313 math operators C<'+'>, C<'-'>, C<'/'>, and C<'*'>:
3317 These commands should work well for most of the token types that perltidy uses
3318 (use B<--dump-token-types> for a list). Also try the B<-D> flag on a short
3319 snippet of code and look at the .DEBUG file to see the tokenization. However,
3320 for a few token types there may be conflicts with hardwired logic which cause
3321 unexpected results. One example is curly braces, which should be controlled
3322 with the parameter B<bl> provided for that purpose.
3324 B<WARNING> Be sure to put these tokens in quotes to avoid having them
3325 misinterpreted by your command shell.
3327 Two additional parameters are available which, though they provide no further
3328 capability, can simplify input are:
3330 B<-baao> or B<--break-after-all-operators>,
3332 B<-bbao> or B<--break-before-all-operators>.
3334 The -baao sets the default to be to break after all of the following operators:
3336 % + - * / x != == >= <= =~ !~ < > | &
3337 = **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x=
3338 . : ? && || and or err xor
3340 and the B<-bbao> flag sets the default to break before all of these operators.
3341 These can be used to define an initial break preference which can be fine-tuned
3342 with the B<-wba> and B<-wbb> flags. For example, to break before all operators
3343 except an B<=> one could use --bbao -wba='=' rather than listing every
3344 single perl operator except B<=> on a -wbb flag.
3348 =item B<-bal=n, --break-after-labels=n>
3350 This flag controls whether or not a line break occurs after a label. There
3351 are three possible values for B<n>:
3353 -bal=0 break if there is a break in the input [DEFAULT]
3354 -bal=1 always break after a label
3355 -bal=2 never break after a label
3368 =head2 Controlling List Formatting
3370 Perltidy attempts to format lists of comma-separated values in tables which
3371 look good. Its default algorithms usually work well, but sometimes they don't.
3372 In this case, there are several methods available to control list formatting.
3374 A very simple way to prevent perltidy from changing the line breaks
3375 within a comma-separated list of values is to insert a blank line,
3376 comment, or side-comment anywhere between the opening and closing
3377 parens (or braces or brackets). This causes perltidy to skip
3378 over its list formatting logic. (The reason is that any of
3379 these items put a constraint on line breaks, and perltidy
3380 needs complete control over line breaks within a container to
3381 adjust a list layout). For example, let us consider
3389 The default formatting, which allows a maximum line length of 80,
3390 will flatten this down to one line:
3392 # perltidy (default)
3393 my @list = ( 1, 1, 1, 1, 2, 1, 1, 3, 3, 1, 1, 4, 6, 4, 1, );
3395 This formatting loses the nice structure. If we place a side comment anywhere
3396 between the opening and closing parens, the original line break points are
3397 retained. For example,
3400 1, # a side comment forces the original line breakpoints to be kept
3407 The side comment can be a single hash symbol without any text.
3408 We could achieve the same result with a blank line or full comment
3409 anywhere between the opening and closing parens. Vertical alignment
3410 of the list items will still occur if possible.
3412 For another possibility see
3413 the -fs flag in L<"Skipping Selected Sections of Code">.
3417 =item B<-boc>, B<--break-at-old-comma-breakpoints>
3419 The B<-boc> flag is another way to prevent comma-separated lists from being
3420 reformatted. Using B<-boc> on the above example, plus additional flags to retain
3421 the original style, yields
3423 # perltidy -boc -lp -pt=2 -vt=1 -vtc=1
3430 A disadvantage of this flag compared to the methods discussed above is that all
3431 tables in the file must already be nicely formatted.
3433 =item B<-mft=n>, B<--maximum-fields-per-table=n>
3435 If the computed number of fields for any table exceeds B<n>, then it
3436 will be reduced to B<n>. The default value for B<n> is a large number,
3437 40. While this value should probably be left unchanged as a general
3438 rule, it might be used on a small section of code to force a list to
3439 have a particular number of fields per line, and then either the B<-boc>
3440 flag could be used to retain this formatting, or a single comment could
3441 be introduced somewhere to freeze the formatting in future applications
3454 =item B<-cab=n>, B<--comma-arrow-breakpoints=n>
3456 A comma which follows a comma arrow, '=>', is given special
3457 consideration. In a long list, it is common to break at all such
3458 commas. This parameter can be used to control how perltidy breaks at
3459 these commas. (However, it will have no effect if old comma breaks are
3460 being forced because B<-boc> is used). The possible values of B<n> are:
3462 n=0 break at all commas after =>
3463 n=1 stable: break at all commas after => if container is open,
3464 EXCEPT FOR one-line containers
3465 n=2 break at all commas after =>, BUT try to form the maximum
3466 one-line container lengths
3467 n=3 do not treat commas after => specially at all
3468 n=4 break everything: like n=0 but ALSO break a short container with
3469 a => not followed by a comma when -vt=0 is used
3470 n=5 stable: like n=1 but ALSO break at open one-line containers when
3471 -vt=0 is used (default)
3473 For example, given the following single line, perltidy by default will
3474 not add any line breaks because it would break the existing one-line
3477 bless { B => $B, Root => $Root } => $package;
3479 Using B<-cab=0> will force a break after each comma-arrow item:
3487 If perltidy is subsequently run with this container broken, then by
3488 default it will break after each '=>' because the container is now
3489 broken. To reform a one-line container, the parameter B<-cab=2> could
3492 The flag B<-cab=3> can be used to prevent these commas from being
3493 treated specially. In this case, an item such as "01" => 31 is
3494 treated as a single item in a table. The number of fields in this table
3495 will be determined by the same rules that are used for any other table.
3500 "01" => 31, "02" => 29, "03" => 31, "04" => 30,
3501 "05" => 31, "06" => 30, "07" => 31, "08" => 31,
3502 "09" => 30, "10" => 31, "11" => 30, "12" => 31
3507 =head2 Adding and Deleting Commas
3511 =item B<-drc>, B<--delete-repeated-commas>
3513 Repeated commas in a list are undesirable and can be removed with this flag.
3514 For example, given this list with a repeated comma
3516 ignoreSpec( $file, "file",, \%spec, \%Rspec );
3518 we can remove it with -drc
3521 ignoreSpec( $file, "file", \%spec, \%Rspec );
3523 Since the default is not to add or delete commas, this feature is off by default and must be requested.
3526 =item B<--want-trailing-commas=s> or B<-wtc=s>, B<--add-trailing-commas> or B<-atc>, and B<--delete-trailing-commas> or B<-dtc>
3528 A trailing comma is a comma following the last item of a list. Perl allows
3529 trailing commas but they are not required. By default, perltidy does not add
3530 or delete trailing commas, but it is possible to manipulate them with the
3531 following set of three related parameters:
3533 --want-trailing-commas=s, -wtc=s - defines where trailing commas are wanted
3534 --add-trailing-commas, -atc - gives permission to add trailing commas to match the style wanted
3535 --delete-trailing-commas, -dtc - gives permission to delete trailing commas which do not match the style wanted
3537 The parameter B<--want-trailing-commas=s>, or B<-wtc=s>, defines a preferred style. The string B<s> indicates which lists should get trailing commas, as follows:
3539 s=0 : no list should have a trailing comma
3540 s=1 or * : every list should have a trailing comma
3541 s=m a multi-line list should have a trailing commas
3542 s=b trailing commas should be 'bare' (comma followed by newline)
3543 s=h lists of key=>value pairs, with about one one '=>' and one ',' per line,
3544 with a bare trailing comma
3545 s=i lists with about one comma per line, with a bare trailing comma
3546 s=' ' or -wtc not defined : leave trailing commas unchanged [DEFAULT].
3548 This parameter by itself only indicates the where trailing commas are
3549 wanted. Perltidy only adds these trailing commas if the flag B<--add-trailing-commas>, or B<-atc> is set. And perltidy only removes unwanted trailing commas
3550 if the flag B<--delete-trailing-commas>, or B<-dtc> is set.
3552 Here are some example parameter combinations and their meanings
3554 -wtc=0 -dtc : delete all trailing commas
3555 -wtc=1 -atc : all lists get trailing commas
3556 -wtc=m -atc : all multi-line lists get trailing commas, but
3557 single line lists remain unchanged.
3558 -wtc=m -dtc : multi-line lists remain unchanged, but
3559 any trailing commas on single line lists are removed.
3560 -wtc=m -atc -dtc : all multi-line lists get trailing commas, and
3561 any trailing commas on single line lists are removed.
3563 For example, given the following input without a trailing comma
3570 we can add a trailing comma after the variable C<$Root> using
3572 # perltidy -wtc=m -atc
3578 This could also be achieved in this case with B<-wtc=b> instead of B<-wtc=m>
3579 because the trailing comma here is bare (separated from its closing brace by a
3580 newline). And it could also be achieved with B<-wtc=h> because this particular
3581 list is a list of key=>value pairs.
3583 The above styles should cover the main of situations of interest, but it is
3584 possible to apply a different style to each type of container token by
3585 including an opening token ahead of the style character in the above table.
3590 means that lists within parens should have multi-line trailing commas, and that
3591 lists within square brackets have bare trailing commas. Since there is no
3592 specification for curly braces in this example, their trailing commas would
3595 For parentheses, an additional item of information which can be given is an
3596 alphanumeric letter which is used to limit the selection further depending on
3597 the type of token immediately before the opening paren. The possible letters
3598 are currently 'k', 'K', 'f', 'F', 'w', and 'W', with these meanings for
3599 matching whatever precedes an opening paren:
3601 'k' matches if the previous nonblank token is a perl built-in keyword (such as 'if', 'while'),
3602 'K' matches if 'k' does not, meaning that the previous token is not a keyword.
3603 'f' matches if the previous token is a function other than a keyword.
3604 'F' matches if 'f' does not.
3605 'w' matches if either 'k' or 'f' match.
3606 'W' matches if 'w' does not.
3608 These are the same codes used for B<--line-up-parentheses-inclusion-list>.
3613 means that trailing commas are wanted for multi-line parenthesized lists following a function call or keyword.
3615 Here are some points to note regarding adding and deleting trailing commas:
3621 For the implementation of these parameters, a B<list> is basically taken to be
3622 a container of items (parens, square brackets, or braces), which is not a code
3623 block, with one or more commas. These parameters only apply to something that
3624 fits this definition of a list.
3626 Note that a paren-less list of parameters is not a list by this definition, so
3627 these parameters have no effect on a peren-less list.
3629 Another consequence is that if the only comma in a list is deleted, then it
3630 cannot later be added back with these parameters because the container no
3631 longer fits this definition of a list. For example, given
3635 and if we remove the comma with
3637 # perltidy -wtc=m -dtc
3640 then we cannot use these trailing comma controls to add this comma back.
3644 By B<multiline> list is meant a list for which the first comma and trailing comma
3645 are on different lines.
3649 A B<bare> trailing comma is a comma which is at the end of a line. That is,
3650 the closing container token follows on a different line. So a list with a
3651 bare trailing comma is a special case of a multi-line list.
3655 The decision regarding whether or not a list is multi-line or bare is
3656 made based on the B<input> stream. In some cases it may take an iteration
3657 or two to reach a final state.
3661 When using these parameters for the first time it is a good idea to practice
3662 on some test scripts and verify that the results are as expected.
3666 Since the default behavior is not to add or delete commas, these parameters
3667 can be useful on a temporary basis for reformatting a script.
3671 =item B<-dwic>, B<--delete-weld-interfering-commas>
3673 If the closing tokens of two nested containers are separated by a comma, then
3674 welding requested with B<--weld-nested-containers> cannot occur. Any commas in
3675 this situation are optional trailing commas and can be removed with B<-dwic>.
3676 For example, a comma in this scipt prevents welding:
3688 Using B<-dwic> removes the comma and allows welding:
3690 # perltidy -wn -dwic
3698 Since the default is not to add or delete commas, this feature is off by default.
3699 Here are some points to note about the B<-dwic> parameter
3705 This operation is not reversible, so please check results of using this parameter carefully.
3709 Removing this type of isolated trailing comma is necessary for welding to be
3710 possible, but not sufficient. So welding will not always occur where these
3717 =head2 Retaining or Ignoring Existing Line Breaks
3719 Several additional parameters are available for controlling the extent
3720 to which line breaks in the input script influence the output script.
3721 In most cases, the default parameter values are set so that, if a choice
3722 is possible, the output style follows the input style. For example, if
3723 a short logical container is broken in the input script, then the
3724 default behavior is for it to remain broken in the output script.
3726 Most of the parameters in this section would only be required for a
3727 one-time conversion of a script from short container lengths to longer
3728 container lengths. The opposite effect, of converting long container
3729 lengths to shorter lengths, can be obtained by temporarily using a short
3730 maximum line length.
3734 =item B<-bol>, B<--break-at-old-logical-breakpoints>
3736 By default, if a logical expression is broken at a C<&&>, C<||>, C<and>,
3737 or C<or>, then the container will remain broken. Also, breaks
3738 at internal keywords C<if> and C<unless> will normally be retained.
3739 To prevent this, and thus form longer lines, use B<-nbol>.
3741 Please note that this flag does not duplicate old logical breakpoints. They
3742 are merely used as a hint with this flag that a statement should remain
3743 broken. Without this flag, perltidy will normally try to combine relatively
3744 short expressions into a single line.
3746 For example, given this snippet:
3748 return unless $cmd = $cmd || ($dot
3749 && $Last_Shell) || &prompt('|');
3751 # perltidy -bol [default]
3759 return unless $cmd = $cmd || ( $dot && $Last_Shell ) || &prompt('|');
3761 =item B<-bom>, B<--break-at-old-method-breakpoints>
3763 By default, a method call arrow C<-E<gt>> is considered a candidate for
3764 a breakpoint, but method chains will fill to the line width before a break is
3765 considered. With B<-bom>, breaks before the arrow are preserved, so if you
3766 have pre-formatted a method chain:
3769 ->related_resultset('CDs')
3770 ->related_resultset('Tracks')
3772 'track.id' => {-ident => 'none_search.id'},
3775 It will B<keep> these breaks, rather than become this:
3777 my $q = $rs->related_resultset('CDs')->related_resultset('Tracks')->search({
3778 'track.id' => {-ident => 'none_search.id'},
3781 This flag will also look for and keep a 'cuddled' style of calls,
3782 in which lines begin with a closing paren followed by a call arrow,
3786 my $q = $rs->related_resultset(
3788 )->related_resultset(
3791 'track.id' => { -ident => 'none_search.id' },
3794 You may want to include the B<-weld-nested-containers> flag in this case to keep
3795 nested braces and parens together, as in the last line.
3797 =item B<-bos>, B<--break-at-old-semicolon-breakpoints>
3799 Semicolons are normally placed at the end of a statement. This means that formatted lines do not normally begin with semicolons. If the input stream has some lines which begin with semicolons, these can be retained by setting this flag. For example, consider
3800 the following two-line input snippet:
3802 $z = sqrt($x**2 + $y**2)
3805 The default formatting will be:
3807 $z = sqrt( $x**2 + $y**2 );
3809 The result using B<perltidy -bos> keeps the isolated semicolon:
3811 $z = sqrt( $x**2 + $y**2 )
3814 The default is not to do this, B<-nbos>.
3817 =item B<-bok>, B<--break-at-old-keyword-breakpoints>
3819 By default, perltidy will retain a breakpoint before keywords which may
3820 return lists, such as C<sort> and <map>. This allows chains of these
3821 operators to be displayed one per line. Use B<-nbok> to prevent
3822 retaining these breakpoints.
3824 =item B<-bot>, B<--break-at-old-ternary-breakpoints>
3826 By default, if a conditional (ternary) operator is broken at a C<:>,
3827 then it will remain broken. To prevent this, and thereby
3828 form longer lines, use B<-nbot>.
3830 =item B<-boa>, B<--break-at-old-attribute-breakpoints>
3832 By default, if an attribute list is broken at a C<:> in the source file, then
3833 it will remain broken. For example, given the following code, the line breaks
3834 at the ':'s will be retained:
3839 : Get('Name' => 'foo') : Set('Name');
3841 If the attributes are on a single line in the source code then they will remain
3842 on a single line if possible.
3844 To prevent this, and thereby always form longer lines, use B<-nboa>.
3846 =item B<Keeping old breakpoints at specific token types>
3848 It is possible to override the choice of line breaks made by perltidy, and
3849 force it to follow certain line breaks in the input stream, with these two
3852 B<-kbb=s> or B<--keep-old-breakpoints-before=s>, and
3854 B<-kba=s> or B<--keep-old-breakpoints-after=s>
3856 These parameters are each followed by a quoted string, B<s>, containing
3857 a list of token types (separated only by spaces). No more than one of each
3858 of these parameters should be specified, because repeating a
3859 command-line parameter always overwrites the previous one before
3860 perltidy ever sees it.
3862 For example, -kbb='=>' means that if an input line begins with a '=>' then the
3863 output script should also have a line break before that token.
3865 For example, given the script:
3870 my ( $self, $x, $y ) = ( shift, @_ );
3874 # perltidy [default]
3875 method 'foo' => [ Int, Int ] => sub {
3876 my ( $self, $x, $y ) = ( shift, @_ );
3880 # perltidy -kbb='=>'
3884 my ( $self, $x, $y ) = ( shift, @_ );
3888 For the container tokens '{', '[' and '(' and, their closing counterparts, use the token symbol. Thus,
3889 the command to keep a break after all opening parens is:
3893 It is possible to be more specific in matching parentheses by preceding them
3894 with a letter. The possible letters are 'k', 'K', 'f', 'F', 'w', and 'W', with
3895 these meanings (these are the same as used in the
3896 B<--weld-nested-exclusion-list> and B<--line-up-parentheses-exclusion-list>
3899 'k' matches if the previous nonblank token is a perl built-in keyword (such as 'if', 'while'),
3900 'K' matches if 'k' does not, meaning that the previous token is not a keyword.
3901 'f' matches if the previous token is a function other than a keyword.
3902 'F' matches if 'f' does not.
3903 'w' matches if either 'k' or 'f' match.
3904 'W' matches if 'w' does not.
3906 So for example the the following parameter will keep breaks after opening function call
3911 B<NOTE>: A request to break before an opening container, such as B<-kbb='('>,
3912 will be silently ignored because it can lead to formatting instability.
3913 Likewise, a request to break after a closing container, such as B<-kba>=')',
3914 will also be silently ignored.
3916 =item B<-iob>, B<--ignore-old-breakpoints>
3918 Use this flag to tell perltidy to ignore existing line breaks to the
3919 maximum extent possible. This will tend to produce the longest possible
3920 containers, regardless of type, which do not exceed the line length
3921 limit. But please note that this parameter has priority over all
3922 other parameters requesting that certain old breakpoints be kept.
3924 To illustrate, consider the following input text:
3928 default => sub { [] },
3931 The default formatting will keep the container broken, giving
3933 # perltidy [default]
3936 default => sub { [] },
3939 If old breakpoints are ignored, the list will be flattened:
3942 has subcmds => ( is => 'ro', default => sub { [] }, );
3944 Besides flattening lists, this parameter also applies to lines broken
3945 at certain logical breakpoints such as 'if' and 'or'.
3947 Even if this is parameter is not used globally, it provides a convenient way to
3948 flatten selected lists from within an editor.
3950 =item B<-kis>, B<--keep-interior-semicolons>
3952 Use the B<-kis> flag to prevent breaking at a semicolon if
3953 there was no break there in the input file. Normally
3954 perltidy places a newline after each semicolon which
3955 terminates a statement unless several statements are
3956 contained within a one-line brace block. To illustrate,
3957 consider the following input lines:
3959 dbmclose(%verb_delim); undef %verb_delim;
3960 dbmclose(%expanded); undef %expanded;
3962 The default is to break after each statement, giving
3964 dbmclose(%verb_delim);
3966 dbmclose(%expanded);
3969 With B<perltidy -kis> the multiple statements are retained:
3971 dbmclose(%verb_delim); undef %verb_delim;
3972 dbmclose(%expanded); undef %expanded;
3974 The statements are still subject to the specified value
3975 of B<maximum-line-length> and will be broken if this
3976 maximum is exceeded.
3980 =head2 Blank Line Control
3982 Blank lines can improve the readability of a script if they are carefully
3983 placed. Perltidy has several commands for controlling the insertion,
3984 retention, and removal of blank lines.
3988 =item B<-fbl>, B<--freeze-blank-lines>
3990 Set B<-fbl> if you want to the blank lines in your script to
3991 remain exactly as they are. The rest of the parameters in
3992 this section may then be ignored. (Note: setting the B<-fbl> flag
3993 is equivalent to setting B<-mbl=0> and B<-kbl=2>).
3995 =item B<-bbc>, B<--blanks-before-comments>
3997 A blank line will be introduced before a full-line comment. This is the
3998 default. Use B<-nbbc> or B<--noblanks-before-comments> to prevent
3999 such blank lines from being introduced.
4001 =item B<-blbs=n>, B<--blank-lines-before-subs=n>
4003 The parameter B<-blbs=n> requests that least B<n> blank lines precede a sub
4004 definition which does not follow a comment and which is more than one-line
4005 long. The default is <-blbs=1>. B<BEGIN> and B<END> blocks are included.
4007 The requested number of blanks statement will be inserted regardless of the
4008 value of B<--maximum-consecutive-blank-lines=n> (B<-mbl=n>) with the exception
4009 that if B<-mbl=0> then no blanks will be output.
4011 This parameter interacts with the value B<k> of the parameter B<--maximum-consecutive-blank-lines=k> (B<-mbl=k>) as follows:
4013 1. If B<-mbl=0> then no blanks will be output. This allows all blanks to be suppressed with a single parameter. Otherwise,
4015 2. If the number of old blank lines in the script is less than B<n> then
4016 additional blanks will be inserted to make the total B<n> regardless of the
4019 3. If the number of old blank lines in the script equals or exceeds B<n> then
4020 this parameter has no effect, however the total will not exceed
4021 value specified on the B<-mbl=k> flag.
4024 =item B<-blbp=n>, B<--blank-lines-before-packages=n>
4026 The parameter B<-blbp=n> requests that least B<n> blank lines precede a package
4027 which does not follow a comment. The default is B<-blbp=1>.
4029 This parameter interacts with the value B<k> of the parameter
4030 B<--maximum-consecutive-blank-lines=k> (B<-mbl=k>) in the same way as described
4031 for the previous item B<-blbs=n>.
4034 =item B<-bbs>, B<--blanks-before-subs>
4036 For compatibility with previous versions, B<-bbs> or B<--blanks-before-subs>
4037 is equivalent to F<-blbp=1> and F<-blbs=1>.
4039 Likewise, B<-nbbs> or B<--noblanks-before-subs>
4040 is equivalent to F<-blbp=0> and F<-blbs=0>.
4042 =item B<-bbb>, B<--blanks-before-blocks>
4044 A blank line will be introduced before blocks of coding delimited by
4045 B<for>, B<foreach>, B<while>, B<until>, and B<if>, B<unless>, in the following
4052 The block is not preceded by a comment.
4056 The block is not a one-line block.
4060 The number of consecutive non-blank lines at the current indentation depth is at least B<-lbl>
4065 This is the default. The intention of this option is to introduce
4066 some space within dense coding.
4067 This is negated with B<-nbbb> or B<--noblanks-before-blocks>.
4069 =item B<-lbl=n> B<--long-block-line-count=n>
4071 This controls how often perltidy is allowed to add blank lines before
4072 certain block types (see previous section). The default is 8. Entering
4073 a value of B<0> is equivalent to entering a very large number.
4075 =item B<-blao=i> or B<--blank-lines-after-opening-block=i>
4077 This control places a minimum of B<i> blank lines B<after> a line which B<ends>
4078 with an opening block brace of a specified type. By default, this only applies
4079 to the block of a named B<sub>, but this can be changed (see B<-blaol> below).
4080 The default is not to do this (B<i=0>).
4082 Please see the note below on using the B<-blao> and B<-blbc> options.
4084 =item B<-blbc=i> or B<--blank-lines-before-closing-block=i>
4086 This control places a minimum of B<i> blank lines B<before> a line which
4087 B<begins> with a closing block brace of a specified type. By default, this
4088 only applies to the block of a named B<sub>, but this can be changed (see
4089 B<-blbcl> below). The default is not to do this (B<i=0>).
4091 =item B<-blaol=s> or B<--blank-lines-after-opening-block-list=s>
4093 The parameter B<s> is a list of block type keywords to which the flag B<-blao>
4094 should apply. The section L<"Specifying Block Types"> explains how to list
4097 =item B<-blbcl=s> or B<--blank-lines-before-closing-block-list=s>
4099 This parameter is a list of block type keywords to which the flag B<-blbc>
4100 should apply. The section L<"Specifying Block Types"> explains how to list
4103 =item B<Note on using the> B<-blao> and B<-blbc> options.
4105 These blank line controls introduce a certain minimum number of blank lines in
4106 the text, but the final number of blank lines may be greater, depending on
4107 values of the other blank line controls and the number of old blank lines. A
4108 consequence is that introducing blank lines with these and other controls
4109 cannot be exactly undone, so some experimentation with these controls is
4110 recommended before using them.
4112 For example, suppose that for some reason we decide to introduce one blank
4113 space at the beginning and ending of all blocks. We could do
4116 perltidy -blao=2 -blbc=2 -blaol='*' -blbcl='*' filename
4118 Now suppose the script continues to be developed, but at some later date we
4119 decide we don't want these spaces after all. We might expect that running with
4120 the flags B<-blao=0> and B<-blbc=0> will undo them. However, by default
4121 perltidy retains single blank lines, so the blank lines remain.
4123 We can easily fix this by telling perltidy to ignore old blank lines by
4124 including the added parameter B<-kbl=0> and rerunning. Then the unwanted blank
4125 lines will be gone. However, this will cause all old blank lines to be
4126 ignored, perhaps even some that were added by hand to improve formatting. So
4127 please be cautious when using these parameters.
4129 =item B<-mbl=n> B<--maximum-consecutive-blank-lines=n>
4131 This parameter specifies the maximum number of consecutive blank lines which
4132 will be output within code sections of a script. The default is n=1. If the
4133 input file has more than n consecutive blank lines, the number will be reduced
4134 to n except as noted above for the B<-blbp> and B<-blbs> parameters. If B<n=0>
4135 then no blank lines will be output (unless all old blank lines are retained
4136 with the B<-kbl=2> flag of the next section).
4138 This flag obviously does not apply to pod sections,
4139 here-documents, and quotes.
4141 =item B<-kbl=n>, B<--keep-old-blank-lines=n>
4143 The B<-kbl=n> flag gives you control over how your existing blank lines are
4146 The possible values of B<n> are:
4148 n=0 ignore all old blank lines
4149 n=1 stable: keep old blanks, but limited by the value of the B<-mbl=n> flag
4150 n=2 keep all old blank lines, regardless of the value of the B<-mbl=n> flag
4152 The default is B<n=1>.
4154 =item B<-sob>, B<--swallow-optional-blank-lines>
4156 This is equivalent to B<kbl=0> and is included for compatibility with
4159 =item B<-nsob>, B<--noswallow-optional-blank-lines>
4161 This is equivalent to B<kbl=1> and is included for compatibility with
4166 B<Controls for blank lines around lines of consecutive keywords>
4168 The parameters in this section provide some control over the placement of blank
4169 lines within and around groups of statements beginning with selected keywords.
4170 These blank lines are called here B<keyword group blanks>, and all of the
4171 parameters begin with B<--keyword-group-blanks*>, or B<-kgb*> for short. The
4172 default settings do not employ these controls but they can be enabled with the
4173 following parameters:
4175 B<-kgbl=s> or B<--keyword-group-blanks-list=s>; B<s> is a quoted string of keywords
4177 B<-kgbs=s> or B<--keyword-group-blanks-size=s>; B<s> gives the number of keywords required to form a group.
4179 B<-kgbb=n> or B<--keyword-group-blanks-before=n>; B<n> = (0, 1, or 2) controls a leading blank
4181 B<-kgba=n> or B<--keyword-group-blanks-after=n>; B<n> = (0, 1, or 2) controls a trailing blank
4183 B<-kgbi> or B<--keyword-group-blanks-inside> is a switch for adding blanks between subgroups
4185 B<-kgbd> or B<--keyword-group-blanks-delete> is a switch for removing initial blank lines between keywords
4187 B<-kgbr=n> or B<--keyword-group-blanks-repeat-count=n> can limit the number of times this logic is applied
4189 In addition, the following abbreviations are available to for simplified usage:
4191 B<-kgb> or B<--keyword-group-blanks> is short for B<-kgbb=2 -kgba=2 kgbi>
4193 B<-nkgb> or B<--nokeyword-group-blanks>, is short for B<-kgbb=1 -kgba=1 nkgbi>
4195 Before describing the meaning of the parameters in detail let us look at an
4196 example which is formatted with default parameter settings.
4198 print "Entering test 2\n";
4200 use Encode qw(from_to encode decode
4201 encode_utf8 decode_utf8
4202 find_encoding is_utf8);
4203 use charnames qw(greek);
4204 my @encodings = grep( /iso-?8859/, Encode::encodings() );
4205 my @character_set = ( '0' .. '9', 'A' .. 'Z', 'a' .. 'z' );
4206 my @source = qw(ascii iso8859-1 cp1250);
4207 my @destiny = qw(cp1047 cp37 posix-bc);
4208 my @ebcdic_sets = qw(cp1047 cp37 posix-bc);
4209 my $str = join( '', map( chr($_), 0x20 .. 0x7E ) );
4210 return unless ($str);
4212 using B<perltidy -kgb> gives:
4214 print "Entering test 2\n";
4215 <----------this blank controlled by -kgbb
4217 use Encode qw(from_to encode decode
4218 encode_utf8 decode_utf8
4219 find_encoding is_utf8);
4220 use charnames qw(greek);
4221 <---------this blank controlled by -kgbi
4222 my @encodings = grep( /iso-?8859/, Encode::encodings() );
4223 my @character_set = ( '0' .. '9', 'A' .. 'Z', 'a' .. 'z' );
4224 my @source = qw(ascii iso8859-1 cp1250);
4225 my @destiny = qw(cp1047 cp37 posix-bc);
4226 my @ebcdic_sets = qw(cp1047 cp37 posix-bc);
4227 my $str = join( '', map( chr($_), 0x20 .. 0x7E ) );
4228 <----------this blank controlled by -kgba
4229 return unless ($str);
4231 Blank lines have been introduced around the B<my> and B<use> sequences. What
4232 happened is that the default keyword list includes B<my> and B<use> but not
4233 B<print> and B<return>. So a continuous sequence of nine B<my> and B<use>
4234 statements was located. This number exceeds the default threshold of five, so
4235 blanks were placed before and after the entire group. Then, since there was
4236 also a subsequence of six B<my> lines, a blank line was introduced to separate
4239 Finer control over blank placement can be achieved by using the individual
4240 parameters rather than the B<-kgb> flag. The individual controls are as follows.
4242 B<-kgbl=s> or B<--keyword-group-blanks-list=s>, where B<s> is a quoted string,
4243 defines the set of keywords which will be formed into groups. The string is a
4244 space separated list of keywords. The default set is B<s="use require local
4245 our my">, but any list of keywords may be used. Comment lines may also be included in a keyword group, even though they are not keywords. To include ordinary block comments, include the symbol B<BC>. To include static block comments (which normally begin with '##'), include the symbol B<SBC>.
4247 B<-kgbs=s> or B<--keyword-group-blanks-size=s>, where B<s> is a string
4248 describing the number of consecutive keyword statements forming a group (Note:
4249 statements separated by blank lines in the input file are considered
4250 consecutive for purposes of this count). If B<s> is an integer then it is the
4251 minimum number required for a group. A maximum value may also be given with
4252 the format B<s=min.max>, where B<min> is the minimum number and B<max> is the
4253 maximum number, and the min and max values are separated by one or more dots.
4254 No groups will be found if the maximum is less than the minimum. The maximum
4255 is unlimited if not given. The default is B<s=5>. Some examples:
4257 s min max number for group
4258 3 3 unlimited 3 or more
4263 There is no really good default value for this parameter. If it is set too
4264 small, then an excessive number of blank lines may be generated. However, some
4265 users may prefer reducing the value somewhat below the default, perhaps to
4268 B<-kgbb=n> or B<--keyword-group-blanks-before=n> specifies whether
4269 a blank should appear before the first line of the group, as follows:
4271 n=0 => (delete) an existing blank line will be removed
4272 n=1 => (stable) no change to the input file is made [DEFAULT]
4273 n=2 => (insert) a blank line is introduced if possible
4275 B<-kgba=n> or B<--keyword-group-blanks-after=n> likewise specifies
4276 whether a blank should appear after the last line of the group, using the same
4277 scheme (0=delete, 1=stable, 2=insert).
4279 B<-kgbi> or B<--keyword-group-blanks-inside> controls
4280 the insertion of blank lines between the first and last statement of the entire
4281 group. If there is a continuous run of a single statement type with more than
4282 the minimum threshold number (as specified with B<-kgbs=s>) then this
4283 switch causes a blank line be inserted between this
4284 subgroup and the others. In the example above this happened between the
4285 B<use> and B<my> statements.
4287 B<-kgbd> or B<--keyword-group-blanks-delete> controls the deletion of any
4288 blank lines that exist in the the group when it is first scanned. When
4289 statements are initially scanned, any existing blank lines are included in the
4290 collection. Any such original blank lines will be deleted before any other
4291 insertions are made when the parameter B<-kgbd> is set. The default is not to
4294 B<-kgbr=n> or B<--keyword-group-blanks-repeat-count=n> specifies B<n>, the
4295 maximum number of times this logic will be applied to any file. The special
4296 value B<n=0> is the same as n=infinity which means it will be applied to an
4297 entire script [Default]. A value B<n=1> could be used to make it apply just
4298 one time for example. This might be useful for adjusting just the B<use>
4299 statements in the top part of a module for example.
4301 B<-kgb> or B<--keyword-group-blanks> is an abbreviation equivalent to setting
4302 B<-kgbb=1 -kgba=1 -kgbi>. This turns on keyword group formatting with a set of
4305 B<-nkgb> or B<--nokeyword-group-blanks> is equivalent to B<-kgbb=0 -kgba
4306 nkgbi>. This flag turns off keyword group blank lines and is the default
4309 Here are a few notes about the functioning of this technique.
4315 These parameters are probably more useful as part of a major code reformatting
4316 operation rather than as a routine formatting operation.
4318 In particular, note that deleting old blank lines with B<-kgbd> is an
4319 irreversible operation so it should be applied with care. Existing blank lines
4320 may be serving an important role in controlling vertical alignment.
4324 Conflicts which arise among these B<kgb*> parameters and other blank line
4325 controls are generally resolved by producing the maximum number of blank lines
4326 implied by any parameter.
4328 For example, if the flags B<--freeze-blank-lines>, or
4329 B<--keep-old-blank-lines=2>, are set, then they have priority over any blank
4330 line deletion implied by the B<-kgb> flags of this section, so no blank lines
4333 For another example, if a keyword group ends at a B<sub> and the flag B<kgba=0> requests no blank line there, but we also have B<--blank-lines-before-subs=2>, then two blank lines will still be introduced before the sub.
4337 The introduction of blank lines does not occur if it would conflict with other
4338 input controls or code validity. For example, a blank line will not be placed
4339 within a here-doc or within a section of code marked with format skipping
4340 comments. And in general, a blank line will only be introduced at the end of a
4341 group if the next statement is a line of code.
4345 The count which is used to determine the group size is not the number of lines
4346 but rather the total number of keywords which are found. Individual statements
4347 with a certain leading keyword may continue on multiple lines, but if any of
4348 these lines is nested more than one level deep then that group will be ended.
4352 The search for groups of lines with similar leading keywords is based on the
4353 input source, not the final formatted source. Consequently, if the source code
4354 is badly formatted, it would be best to make a first formatting pass without
4361 A style refers to a convenient collection of existing parameters.
4365 =item B<-gnu>, B<--gnu-style>
4367 B<-gnu> gives an approximation to the GNU Coding Standards (which do
4368 not apply to perl) as they are sometimes implemented. At present, this
4369 style overrides the default style with the following parameters:
4371 -lp -bl -noll -pt=2 -bt=2 -sbt=2 -icp
4373 To use this style with B<-xlp> instead of B<-lp> use B<-gnu -xlp>.
4375 =item B<-pbp>, B<--perl-best-practices>
4377 B<-pbp> is an abbreviation for the parameters in the book B<Perl Best Practices>
4380 -l=78 -i=4 -ci=4 -st -se -vt=2 -cti=0 -pt=1 -bt=1 -sbt=1 -bbt=1 -nsfs -nolq
4381 -wbb="% + - * / x != == >= <= =~ !~ < > | & =
4382 **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x="
4384 Please note that this parameter set includes -st and -se flags, which make
4385 perltidy act as a filter on one file only. These can be overridden by placing
4386 B<-nst> and/or B<-nse> after the -pbp parameter.
4388 Also note that the value of continuation indentation, -ci=4, is equal to the
4389 value of the full indentation, -i=4. It is recommended that the either (1) the
4390 parameter B<-ci=2> be used instead, or the flag B<-xci> be set. This will help
4391 show structure, particularly when there are ternary statements. The following
4392 snippet illustrates these options.
4397 : $type eq 'item' ? "the $section entry"
4398 : "the section on $section"
4402 ? ( $section ? ' in ' : '' ) . "the $page$page_ext manpage"
4403 : ' elsewhere in this document'
4406 # perltidy -pbp -ci=2
4409 : $type eq 'item' ? "the $section entry"
4410 : "the section on $section"
4414 ? ( $section ? ' in ' : '' ) . "the $page$page_ext manpage"
4415 : ' elsewhere in this document'
4418 # perltidy -pbp -xci
4421 : $type eq 'item' ? "the $section entry"
4422 : "the section on $section"
4425 ? ( $section ? ' in ' : '' ) . "the $page$page_ext manpage"
4426 : ' elsewhere in this document'
4429 The B<-xci> flag was developed after the B<-pbp> parameters were published so you need
4430 to include it separately.
4432 =item B<One-line blocks>
4434 There are a few points to note regarding one-line blocks. A one-line
4435 block is something like this,
4437 if ( -e $file ) { print "'$file' exists\n" }
4439 where the contents within the curly braces is short enough to fit
4442 With few exceptions, perltidy retains existing one-line blocks, if it
4443 is possible within the line-length constraint, but it does not attempt
4444 to form new ones. In other words, perltidy will try to follow the
4445 one-line block style of the input file.
4447 If an existing one-line block is longer than the maximum line length,
4448 however, it will be broken into multiple lines. When this happens, perltidy
4449 checks for and adds any optional terminating semicolon (unless the B<-nasc>
4450 option is used) if the block is a code block.
4452 The main exception is that perltidy will attempt to form new one-line
4453 blocks following the keywords C<map>, C<eval>, and C<sort>, because
4454 these code blocks are often small and most clearly displayed in a single
4457 One-line block rules can conflict with the cuddled-else option. When
4458 the cuddled-else option is used, perltidy retains existing one-line
4459 blocks, even if they do not obey cuddled-else formatting.
4461 Occasionally, when one-line blocks get broken because they exceed the
4462 available line length, the formatting will violate the requested brace style.
4463 If this happens, reformatting the script a second time should correct
4466 Sometimes it might be desirable to convert a script to have one-line blocks
4467 whenever possible. Although there is currently no flag for this, a simple
4468 workaround is to execute perltidy twice, once with the flag B<-noadd-newlines>
4469 and then once again with normal parameters, like this:
4471 cat infile | perltidy -nanl | perltidy >outfile
4473 When executed on this snippet
4476 die "failed to execute: $!\n";
4479 print "Had enough.\n";
4480 die "failed to execute: $!\n";
4485 if ( $? == -1 ) { die "failed to execute: $!\n"; }
4487 print "Had enough.\n";
4488 die "failed to execute: $!\n";
4491 This shows that blocks with a single statement become one-line blocks.
4493 =item B<-olbs=n>, B<--one-line-block-semicolons=n>
4495 This flag controls the placement of semicolons at the end of one-line blocks.
4496 Semicolons are optional before a closing block brace, and frequently they are
4497 omitted at the end of a one-line block containing just a single statement.
4498 By default, perltidy follows the input file regarding these semicolons,
4499 but this behavior can be controlled by this flag. The values of n are:
4501 n=0 remove terminal semicolons in one-line blocks having a single statement
4502 n=1 stable; keep input file placement of terminal semicolons [DEFAULT ]
4503 n=2 add terminal semicolons in all one-line blocks
4505 Note that the B<n=2> option has no effect if adding semicolons is prohibited
4506 with the B<-nasc> flag. Also not that while B<n=2> adds missing semicolons to
4507 all one-line blocks, regardless of complexity, the B<n=0> option only removes
4508 ending semicolons which terminate one-line blocks containing just one
4509 semicolon. So these two options are not exact inverses.
4511 =item B<-olbn=n>, B<--one-line-block-nesting=n>
4513 Nested one-line blocks are lines with code blocks which themselves contain code
4514 blocks. For example, the following line is a nested one-line block.
4516 foreach (@list) { if ($_ eq $asked_for) { last } ++$found }
4518 The default behavior is to break such lines into multiple lines, but this
4519 behavior can be controlled with this flag. The values of n are:
4521 n=0 break nested one-line blocks into multiple lines [DEFAULT]
4522 n=1 stable: keep existing nested-one line blocks intact
4524 For the above example, the default formatting (B<-olbn=0>) is
4527 if ( $_ eq $asked_for ) { last }
4531 If the parameter B<-olbn=1> is given, then the line will be left intact if it
4532 is a single line in the source, or it will be broken into multiple lines if it
4533 is broken in multiple lines in the source.
4539 =head2 Controlling Vertical Alignment
4541 Vertical alignment refers to lining up certain symbols in a list of consecutive
4542 similar lines to improve readability. For example, the "fat commas" are
4543 aligned in the following statement:
4546 PeerAddr => join( ".", @port[ 0 .. 3 ] ),
4547 PeerPort => $port[4] * 256 + $port[5],
4551 Vertical alignment can be completely turned off using the B<-novalign> flag
4552 mentioned below. However, vertical alignment can be forced to
4553 stop and restart by selectively introducing blank lines. For example, a blank
4554 has been inserted in the following code to keep somewhat similar things
4558 'format' => [ 'tidy', 'html', 'user' ],
4559 'output-line-ending' => [ 'dos', 'win', 'mac', 'unix' ],
4560 'character-encoding' => [ 'none', 'utf8' ],
4562 'block-brace-tightness' => [ 0, 2 ],
4563 'brace-tightness' => [ 0, 2 ],
4564 'paren-tightness' => [ 0, 2 ],
4565 'square-bracket-tightness' => [ 0, 2 ],
4568 Vertical alignment is implemented by locally increasing an existing blank space
4569 to produce alignment with an adjacent line. It cannot occur if there is no
4570 blank space to increase. So if a particular space is removed by one of the
4571 existing controls then vertical alignment cannot occur. Likewise, if a space is
4572 added with one of the controls, then vertical alignment might occur.
4576 # perltidy -nwls='=>'
4578 PeerAddr=> join( ".", @port[ 0 .. 3 ] ),
4579 PeerPort=> $port[4] * 256 + $port[5],
4585 =item B<Completely turning off vertical alignment with -novalign>
4587 The default is to use vertical alignment, but vertical alignment can be
4588 completely turned of with the B<-novalign> flag.
4590 A lower level of control of vertical alignment is possible with three parameters
4591 B<-vc>, B<-vsc>, and B<-vbc>. These independently control alignment
4592 of code, side comments and block comments. They are described in the
4595 The parameter B<-valign> is in fact an alias for B<-vc -vsc -vbc>, and its
4596 negative B<-novalign> is an alias for B<-nvc -nvsc -nvbc>.
4598 =item B<Controlling code alignment with --valign-code or -vc>
4600 The B<-vc> flag enables alignment of code symbols such as B<=>. The default is B<-vc>.
4601 For detailed control of which symbols to align, see the B<-valign-exclude-list> parameter
4604 =item B<Controlling side comment alignment with --valign-side-comments or -vsc>
4606 The B<-vsc> flag enables alignment of side comments and is enabled by default. If side
4607 comment alignment is disabled with B<-nvsc> they will appear at a fixed space from the
4608 preceding code token. The default is B<-vsc>
4610 =item B<Controlling block comment alignment with --valign-block-comments or -vbc>
4612 When B<-vbc> is enabled, block comments can become aligned for example if one
4613 comment of a consecutive sequence of comments becomes outdented due a length in
4614 excess of the maximum line length. If this occurs, the entire group of
4615 comments will remain aligned and be outdented by the same amount. This coordinated
4616 alignment will not occur if B<-nvbc> is set. The default is B<-vbc>.
4618 =item B<Finer alignment control with --valign-exclusion-list=s or -vxl=s and --valign-inclusion-list=s or -vil=s>
4620 More detailed control of alignment types is available with these two
4621 parameters. Most of the vertical alignments in typical programs occur at one
4622 of the tokens ',', '=', and '=>', but many other alignments are possible and are given in the following list:
4624 = **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x=
4625 { ( ? : , ; => && || ~~ !~~ =~ !~ // <=> -> q
4626 if unless and or err for foreach while until
4628 These alignment types correspond to perl symbols, operators and keywords except
4629 for 'q', which refers to the special case of alignment in a 'use' statement of
4630 qw quotes and empty parens.
4632 They are all enabled by default, but they can be selectively disabled by including one or more of these tokens in the space-separated list B<valign-exclusion-list=s>.
4633 For example, the following would prevent alignment at B<=> and B<if>:
4635 --valign-exclusion-list='= if'
4637 If it is simpler to specify only the token types which are to be aligned, then
4638 include the types which are to be aligned in the list of B<--valign-inclusion-list>.
4639 In that case you may leave the B<valign-exclusion-list> undefined, or use the special symbol B<*> for the exclusion list.
4640 For example, the following parameters enable alignment only at commas and 'fat commas':
4642 --valign-inclusion-list=', =>'
4643 --valign-exclusion-list='*' ( this is optional and may be omitted )
4645 These parameter lists should consist of space-separated tokens from the above
4646 list of possible alignment tokens, or a '*'. If an unrecognized token
4647 appears, it is simply ignored. And if a specific token is entered in both lists by
4648 mistake then the exclusion list has priority.
4650 The default values of these parameters enable all alignments and are equivalent to
4652 --valign-exclusion-list=' '
4653 --valign-inclusion-list='*'
4655 To illustrate, consider the following snippet with default formatting
4658 $co_description = ($color) ? 'bold cyan' : ''; # description
4659 $co_prompt = ($color) ? 'bold green' : ''; # prompt
4660 $co_unused = ($color) ? 'on_green' : 'reverse'; # unused
4662 To exclude all alignments except the equals (i.e., include only equals) we could use:
4665 $co_description = ($color) ? 'bold cyan' : ''; # description
4666 $co_prompt = ($color) ? 'bold green' : ''; # prompt
4667 $co_unused = ($color) ? 'on_green' : 'reverse'; # unused
4669 To exclude only the equals we could use:
4672 $co_description = ($color) ? 'bold cyan' : ''; # description
4673 $co_prompt = ($color) ? 'bold green' : ''; # prompt
4674 $co_unused = ($color) ? 'on_green' : 'reverse'; # unused
4676 Notice in this last example that although only the equals alignment was
4677 excluded, the ternary alignments were also lost. This happens because the
4678 vertical aligner sweeps from left-to-right and usually stops if an important
4679 alignment cannot be made for some reason.
4681 But also notice that side comments remain aligned because their alignment is
4682 controlled separately with the parameter B<--valign-side_comments> described above.
4686 =head2 Other Controls
4690 =item B<Deleting selected text>
4692 Perltidy can selectively delete comments and/or pod documentation. The
4693 command B<-dac> or B<--delete-all-comments> will delete all comments
4694 B<and> all pod documentation, leaving just code and any leading system
4697 The command B<-dp> or B<--delete-pod> will remove all pod documentation
4700 Two commands which remove comments (but not pod) are: B<-dbc> or
4701 B<--delete-block-comments> and B<-dsc> or B<--delete-side-comments>.
4702 (Hanging side comments will be deleted with side comments here.)
4704 When side comments are deleted, any special control side comments for
4705 non-indenting braces will be retained unless they are deactivated with
4708 The negatives of these commands also work, and are the defaults. When
4709 block comments are deleted, any leading 'hash-bang' will be retained.
4710 Also, if the B<-x> flag is used, any system commands before a leading
4711 hash-bang will be retained (even if they are in the form of comments).
4713 =item B<Writing selected text to a file>
4715 When perltidy writes a formatted text file, it has the ability to also
4716 send selected text to a file with a F<.TEE> extension. This text can
4717 include comments and pod documentation.
4719 The command B<-tac> or B<--tee-all-comments> will write all comments
4720 B<and> all pod documentation.
4722 The command B<-tp> or B<--tee-pod> will write all pod documentation (but
4725 The commands which write comments (but not pod) are: B<-tbc> or
4726 B<--tee-block-comments> and B<-tsc> or B<--tee-side-comments>.
4727 (Hanging side comments will be written with side comments here.)
4729 The negatives of these commands also work, and are the defaults.
4731 =item B<Using a F<.perltidyrc> command file>
4733 If you use perltidy frequently, you probably won't be happy until you
4734 create a F<.perltidyrc> file to avoid typing commonly-used parameters.
4735 Perltidy will first look in your current directory for a command file
4736 named F<.perltidyrc>. If it does not find one, it will continue looking
4737 for one in other standard locations.
4739 These other locations are system-dependent, and may be displayed with
4740 the command C<perltidy -dpro>. Under Unix systems, it will first look
4741 for an environment variable B<PERLTIDY>. Then it will look for a
4742 F<.perltidyrc> file in the home directory, and then for a system-wide
4743 file F</usr/local/etc/perltidyrc>, and then it will look for
4744 F</etc/perltidyrc>. Note that these last two system-wide files do not
4745 have a leading dot. Further system-dependent information will be found
4746 in the INSTALL file distributed with perltidy.
4748 Under Windows, perltidy will also search for a configuration file named F<perltidy.ini> since Windows does not allow files with a leading period (.).
4749 Use C<perltidy -dpro> to see the possible locations for your system.
4750 An example might be F<C:\Documents and Settings\All Users\perltidy.ini>.
4752 Another option is the use of the PERLTIDY environment variable.
4753 The method for setting environment variables depends upon the version of
4754 Windows that you are using. Instructions for Windows 95 and later versions can
4757 http://www.netmanage.com/000/20021101_005_tcm21-6336.pdf
4759 Under Windows NT / 2000 / XP the PERLTIDY environment variable can be placed in
4760 either the user section or the system section. The later makes the
4761 configuration file common to all users on the machine. Be sure to enter the
4762 full path of the configuration file in the value of the environment variable.
4763 Ex. PERLTIDY=C:\Documents and Settings\perltidy.ini
4765 The configuration file is free format, and simply a list of parameters, just as
4766 they would be entered on a command line. Any number of lines may be used, with
4767 any number of parameters per line, although it may be easiest to read with one
4768 parameter per line. Comment text begins with a #, and there must
4769 also be a space before the # for side comments. It is a good idea to
4770 put complex parameters in either single or double quotes.
4772 Here is an example of a F<.perltidyrc> file:
4774 # This is a simple of a .perltidyrc configuration file
4775 # This implements a highly spaced style
4776 -se # errors to standard error output
4777 -w # show all warnings
4778 -bl # braces on new lines
4779 -pt=0 # parens not tight at all
4780 -bt=0 # braces not tight
4781 -sbt=0 # square brackets not tight
4783 The parameters in the F<.perltidyrc> file are installed first, so any
4784 parameters given on the command line will have priority over them.
4786 To avoid confusion, perltidy ignores any command in the .perltidyrc
4787 file which would cause some kind of dump and an exit. These are:
4789 -h -v -ddf -dln -dop -dsn -dtt -dwls -dwrs -ss
4791 There are several options may be helpful in debugging a F<.perltidyrc>
4798 A very helpful command is B<--dump-profile> or B<-dpro>. It writes a
4799 list of all configuration filenames tested to standard output, and
4800 if a file is found, it dumps the content to standard output before
4801 exiting. So, to find out where perltidy looks for its configuration
4802 files, and which one if any it selects, just enter
4808 It may be simplest to develop and test configuration files with
4809 alternative names, and invoke them with B<-pro=filename> on the command
4810 line. Then rename the desired file to F<.perltidyrc> when finished.
4814 The parameters in the F<.perltidyrc> file can be switched off with
4815 the B<-npro> option.
4819 The commands B<--dump-options>, B<--dump-defaults>, B<--dump-long-names>,
4820 and B<--dump-short-names>, all described below, may all be helpful.
4824 =item B<Creating a new abbreviation>
4826 A special notation is available for use in a F<.perltidyrc> file
4827 for creating an abbreviation for a group
4828 of options. This can be used to create a
4829 shorthand for one or more styles which are frequently, but not always,
4830 used. The notation is to group the options within curly braces which
4831 are preceded by the name of the alias (without leading dashes), like this:
4838 where B<newword> is the abbreviation, and B<opt1>, etc, are existing parameters
4839 I<or other abbreviations>. The main syntax requirement is that the new
4840 abbreviation along with its opening curly brace must begin on a new line.
4841 Space before and after the curly braces is optional.
4843 For a specific example, the following line
4845 oneliner { --maximum-line-length=0 --noadd-newlines --noadd-terminal-newline}
4847 or equivalently with abbreviations
4849 oneliner { -l=0 -nanl -natnl }
4851 could be placed in a F<.perltidyrc> file to temporarily override the maximum
4852 line length with a large value, to temporarily prevent new line breaks from
4853 being added, and to prevent an extra newline character from being added the
4854 file. All other settings in the F<.perltidyrc> file still apply. Thus it
4855 provides a way to format a long 'one liner' when perltidy is invoked with
4857 perltidy --oneliner ...
4859 (Either C<-oneliner> or C<--oneliner> may be used).
4861 =item Skipping leading non-perl commands with B<-x> or B<--look-for-hash-bang>
4863 If your script has leading lines of system commands or other text which
4864 are not valid perl code, and which are separated from the start of the
4865 perl code by a "hash-bang" line, ( a line of the form C<#!...perl> ),
4866 you must use the B<-x> flag to tell perltidy not to parse and format any
4867 lines before the "hash-bang" line. This option also invokes perl with a
4868 -x flag when checking the syntax. This option was originally added to
4869 allow perltidy to parse interactive VMS scripts, but it should be used
4870 for any script which is normally invoked with C<perl -x>.
4872 Please note: do not use this flag unless you are sure your script needs it.
4873 Parsing errors can occur if it does not have a hash-bang, or, for example, if
4874 the actual first hash-bang is in a here-doc. In that case a parsing error will
4875 occur because the tokenization will begin in the middle of the here-doc.
4877 =item B<Making a file unreadable>
4879 The goal of perltidy is to improve the readability of files, but there
4880 are two commands which have the opposite effect, B<--mangle> and
4881 B<--extrude>. They are actually
4882 merely aliases for combinations of other parameters. Both of these
4883 strip all possible whitespace, but leave comments and pod documents,
4884 so that they are essentially reversible. The
4885 difference between these is that B<--mangle> puts the fewest possible
4886 line breaks in a script while B<--extrude> puts the maximum possible.
4887 Note that these options do not provided any meaningful obfuscation, because
4888 perltidy can be used to reformat the files. They were originally
4889 developed to help test the tokenization logic of perltidy, but they
4891 One use for B<--mangle> is the following:
4893 perltidy --mangle myfile.pl -st | perltidy -o myfile.pl.new
4895 This will form the maximum possible number of one-line blocks (see next
4896 section), and can sometimes help clean up a badly formatted script.
4898 A similar technique can be used with B<--extrude> instead of B<--mangle>
4899 to make the minimum number of one-line blocks.
4901 Another use for B<--mangle> is to combine it with B<-dac> to reduce
4902 the file size of a perl script.
4906 The following flags are available for debugging:
4908 B<--dump-cuddled-block-list> or B<-dcbl> will dump to standard output the
4909 internal hash of cuddled block types created by a B<-cuddled-block-list> input
4912 B<--dump-defaults> or B<-ddf> will write the default option set to standard output and quit
4914 B<--dump-profile> or B<-dpro> will write the name of the current
4915 configuration file and its contents to standard output and quit.
4917 B<--dump-options> or B<-dop> will write current option set to standard
4920 B<--dump-long-names> or B<-dln> will write all command line long names (passed
4921 to Get_options) to standard output and quit.
4923 B<--dump-short-names> or B<-dsn> will write all command line short names
4924 to standard output and quit.
4926 B<--dump-token-types> or B<-dtt> will write a list of all token types
4927 to standard output and quit.
4929 B<--dump-want-left-space> or B<-dwls> will write the hash %want_left_space
4930 to standard output and quit. See the section on controlling whitespace
4933 B<--dump-want-right-space> or B<-dwrs> will write the hash %want_right_space
4934 to standard output and quit. See the section on controlling whitespace
4937 B<--no-memoize> or B<-nmem> will turn of memoizing.
4938 Memoization can reduce run time when running perltidy repeatedly in a
4939 single process. It is on by default but can be deactivated for
4940 testing with B<-nmem>.
4942 B<--no-timestamp> or B<-nts> will eliminate any time stamps in output files to prevent
4943 differences in dates from causing test installation scripts to fail. There are just
4944 a couple of places where timestamps normally occur. One is in the headers of
4945 html files, and another is when the B<-cscw> option is selected. The default is
4946 to allow timestamps (B<--timestamp> or B<-ts>).
4948 B<--file-size-order> or B<-fso> will cause files to be processed in order of
4949 increasing size, when multiple files are being processed. This is useful
4950 during program development, when large numbers of files with varying sizes are
4951 processed, because it can reduce virtual memory usage.
4953 B<--maximum-file-size-mb=n> or B<-maxfs=n> specifies the maximum file size in
4954 megabytes that perltidy will attempt to format. This parameter is provided to
4955 avoid causing system problems by accidentally attempting to format an extremely
4956 large data file. Most perl scripts are less than about 2 MB in size. The
4957 integer B<n> has a default value of 10, so perltidy will skip formatting files
4958 which have a size greater than 10 MB. The command to increase the limit to 20
4959 MB for example would be
4963 This only applies to files specified by filename on the command line.
4965 B<--maximum-level-errors=n> or B<-maxle=n> specifies the maximum number of
4966 indentation level errors are allowed before perltidy skips formatting and just
4967 outputs a file verbatim. The default is B<n=1>. This means that if the final
4968 indentation of a script differs from the starting indentation by more than 1
4969 levels, the file will be output verbatim. To avoid formatting if there are any
4970 indentation level errors use -maxle=0. To skip this check you can either set n
4971 equal to a large number, such as B<n=100>, or set B<n=-1>.
4973 For example, the following script has level error of 3 and will be output verbatim
4975 Input and default output:
4984 B<--maximum-unexpected-errors=n> or B<-maxue=n> specifies the maximum number of
4985 unexpected tokenization errors are allowed before formatting is skipped and a
4986 script is output verbatim. The intention is to avoid accidentally formatting
4987 a non-perl script, such as an html file for example. This check can be turned
4988 off by setting B<n=0>.
4990 A recommended value is B<n=3>. However, the default is B<n=0> (skip this check)
4991 to avoid causing problems with scripts which have extended syntaxes.
4993 B<-DEBUG> will write a file with extension F<.DEBUG> for each input file
4994 showing the tokenization of all lines of code.
4996 =item B<Working with MakeMaker, AutoLoader and SelfLoader>
4998 The first $VERSION line of a file which might be eval'd by MakeMaker
4999 is passed through unchanged except for indentation.
5000 Use B<--nopass-version-line>, or B<-npvl>, to deactivate this feature.
5002 If the AutoLoader module is used, perltidy will continue formatting
5003 code after seeing an __END__ line.
5004 Use B<--nolook-for-autoloader>, or B<-nlal>, to deactivate this feature.
5006 Likewise, if the SelfLoader module is used, perltidy will continue formatting
5007 code after seeing a __DATA__ line.
5008 Use B<--nolook-for-selfloader>, or B<-nlsl>, to deactivate this feature.
5010 =item B<Working around problems with older version of Perl>
5012 Perltidy contains a number of rules which help avoid known subtleties
5013 and problems with older versions of perl, and these rules always
5014 take priority over whatever formatting flags have been set. For example,
5015 perltidy will usually avoid starting a new line with a bareword, because
5016 this might cause problems if C<use strict> is active.
5018 There is no way to override these rules.
5026 =item The B<-html> master switch
5028 The flag B<-html> causes perltidy to write an html file with extension
5029 F<.html>. So, for example, the following command
5031 perltidy -html somefile.pl
5033 will produce a syntax-colored html file named F<somefile.pl.html>
5034 which may be viewed with a browser.
5036 B<Please Note>: In this case, perltidy does not do any formatting to the
5037 input file, and it does not write a formatted file with extension
5038 F<.tdy>. This means that two perltidy runs are required to create a
5039 fully reformatted, html copy of a script.
5041 =item The B<-pre> flag for code snippets
5043 When the B<-pre> flag is given, only the pre-formatted section, within
5044 the <PRE> and </PRE> tags, will be output. This simplifies inclusion
5045 of the output in other files. The default is to output a complete
5048 =item The B<-nnn> flag for line numbering
5050 When the B<-nnn> flag is given, the output lines will be numbered.
5052 =item The B<-toc>, or B<--html-table-of-contents> flag
5054 By default, a table of contents to packages and subroutines will be
5055 written at the start of html output. Use B<-ntoc> to prevent this.
5056 This might be useful, for example, for a pod document which contains a
5057 number of unrelated code snippets. This flag only influences the code
5058 table of contents; it has no effect on any table of contents produced by
5059 pod2html (see next item).
5061 =item The B<-pod>, or B<--pod2html> flag
5063 There are two options for formatting pod documentation. The default is
5064 to pass the pod through the Pod::Html module (which forms the basis of
5065 the pod2html utility). Any code sections are formatted by perltidy, and
5066 the results then merged. Note: perltidy creates a temporary file when
5067 Pod::Html is used; see L<"FILES">. Also, Pod::Html creates temporary
5068 files for its cache.
5070 NOTE: Perltidy counts the number of C<=cut> lines, and either moves the
5071 pod text to the top of the html file if there is one C<=cut>, or leaves
5072 the pod text in its original order (interleaved with code) otherwise.
5074 Most of the flags accepted by pod2html may be included in the perltidy
5075 command line, and they will be passed to pod2html. In some cases,
5076 the flags have a prefix C<pod> to emphasize that they are for the
5077 pod2html, and this prefix will be removed before they are passed to
5078 pod2html. The flags which have the additional C<pod> prefix are:
5080 --[no]podheader --[no]podindex --[no]podrecurse --[no]podquiet
5081 --[no]podverbose --podflush
5083 The flags which are unchanged from their use in pod2html are:
5085 --backlink=s --cachedir=s --htmlroot=s --libpods=s --title=s
5086 --podpath=s --podroot=s
5088 where 's' is an appropriate character string. Not all of these flags are
5089 available in older versions of Pod::Html. See your Pod::Html documentation for
5092 The alternative, indicated with B<-npod>, is not to use Pod::Html, but
5093 rather to format pod text in italics (or whatever the stylesheet
5094 indicates), without special html markup. This is useful, for example,
5095 if pod is being used as an alternative way to write comments.
5097 =item The B<-frm>, or B<--frames> flag
5099 By default, a single html output file is produced. This can be changed
5100 with the B<-frm> option, which creates a frame holding a table of
5101 contents in the left panel and the source code in the right side. This
5102 simplifies code browsing. Assume, for example, that the input file is
5103 F<MyModule.pm>. Then, for default file extension choices, these three
5104 files will be created:
5106 MyModule.pm.html - the frame
5107 MyModule.pm.toc.html - the table of contents
5108 MyModule.pm.src.html - the formatted source code
5110 Obviously this file naming scheme requires that output be directed to a real
5111 file (as opposed to, say, standard output). If this is not the
5112 case, or if the file extension is unknown, the B<-frm> option will be
5115 =item The B<-text=s>, or B<--html-toc-extension> flag
5117 Use this flag to specify the extra file extension of the table of contents file
5118 when html frames are used. The default is "toc".
5119 See L<"Specifying File Extensions">.
5121 =item The B<-sext=s>, or B<--html-src-extension> flag
5123 Use this flag to specify the extra file extension of the content file when html
5124 frames are used. The default is "src".
5125 See L<"Specifying File Extensions">.
5127 =item The B<-hent>, or B<--html-entities> flag
5129 This flag controls the use of Html::Entities for html formatting. By
5130 default, the module Html::Entities is used to encode special symbols.
5131 This may not be the right thing for some browser/language
5132 combinations. Use --nohtml-entities or -nhent to prevent this.
5134 =item B<Style Sheets>
5136 Style sheets make it very convenient to control and adjust the
5137 appearance of html pages. The default behavior is to write a page of
5138 html with an embedded style sheet.
5140 An alternative to an embedded style sheet is to create a page with a
5141 link to an external style sheet. This is indicated with the
5142 B<-css=filename>, where the external style sheet is F<filename>. The
5143 external style sheet F<filename> will be created if and only if it does
5144 not exist. This option is useful for controlling multiple pages from a
5147 To cause perltidy to write a style sheet to standard output and exit,
5148 use the B<-ss>, or B<--stylesheet>, flag. This is useful if the style
5149 sheet could not be written for some reason, such as if the B<-pre> flag
5150 was used. Thus, for example,
5152 perltidy -html -ss >mystyle.css
5154 will write a style sheet with the default properties to file
5157 The use of style sheets is encouraged, but a web page without a style
5158 sheets can be created with the flag B<-nss>. Use this option if you
5159 must to be sure that older browsers (roughly speaking, versions prior to
5160 4.0 of Netscape Navigator and Internet Explorer) can display the
5161 syntax-coloring of the html files.
5163 =item B<Controlling HTML properties>
5165 Note: It is usually more convenient to accept the default properties
5166 and then edit the stylesheet which is produced. However, this section
5167 shows how to control the properties with flags to perltidy.
5169 Syntax colors may be changed from their default values by flags of the either
5170 the long form, B<-html-color-xxxxxx=n>, or more conveniently the short form,
5171 B<-hcx=n>, where B<xxxxxx> is one of the following words, and B<x> is the
5172 corresponding abbreviation:
5175 ---------- -------- --
5178 identifier identifier i
5179 bareword, function bareword w
5181 quite, pattern quote q
5182 here doc text here-doc-text h
5183 here doc target here-doc-target hh
5184 punctuation punctuation pu
5186 structural braces structure s
5187 semicolon semicolon sc
5191 sub definition name subroutine m
5192 pod text pod-text pd
5194 A default set of colors has been defined, but they may be changed by providing
5195 values to any of the following parameters, where B<n> is either a 6 digit
5196 hex RGB color value or an ascii name for a color, such as 'red'.
5198 To illustrate, the following command will produce an html
5199 file F<somefile.pl.html> with "aqua" keywords:
5201 perltidy -html -hck=00ffff somefile.pl
5203 and this should be equivalent for most browsers:
5205 perltidy -html -hck=aqua somefile.pl
5207 Perltidy merely writes any non-hex names that it sees in the html file.
5208 The following 16 color names are defined in the HTML 3.2 standard:
5227 Many more names are supported in specific browsers, but it is safest
5228 to use the hex codes for other colors. Helpful color tables can be
5229 located with an internet search for "HTML color tables".
5231 Besides color, two other character attributes may be set: bold, and italics.
5232 To set a token type to use bold, use the flag
5233 B<--html-bold-xxxxxx> or B<-hbx>, where B<xxxxxx> or B<x> are the long
5234 or short names from the above table. Conversely, to set a token type to
5235 NOT use bold, use B<--nohtml-bold-xxxxxx> or B<-nhbx>.
5237 Likewise, to set a token type to use an italic font, use the flag
5238 B<--html-italic-xxxxxx> or B<-hix>, where again B<xxxxxx> or B<x> are the
5239 long or short names from the above table. And to set a token type to
5240 NOT use italics, use B<--nohtml-italic-xxxxxx> or B<-nhix>.
5242 For example, to use bold braces and lime color, non-bold, italics keywords the
5243 following command would be used:
5245 perltidy -html -hbs -hck=00FF00 -nhbk -hik somefile.pl
5247 The background color can be specified with B<--html-color-background=n>,
5248 or B<-hcbg=n> for short, where n is a 6 character hex RGB value. The
5249 default color of text is the value given to B<punctuation>, which is
5252 Here are some notes and hints:
5254 1. If you find a preferred set of these parameters, you may want
5255 to create a F<.perltidyrc> file containing them. See the perltidy man
5256 page for an explanation.
5258 2. Rather than specifying values for these parameters, it is probably
5259 easier to accept the defaults and then edit a style sheet. The style
5260 sheet contains comments which should make this easy.
5262 3. The syntax-colored html files can be very large, so it may be best to
5263 split large files into smaller pieces to improve download times.
5267 =head1 SOME COMMON INPUT CONVENTIONS
5269 =head2 Specifying Block Types
5271 Several parameters which refer to code block types may be customized by also
5272 specifying an associated list of block types. The type of a block is the name
5273 of the keyword which introduces that block, such as B<if>, B<else>, or B<sub>.
5274 An exception is a labeled block, which has no keyword, and should be specified
5275 with just a colon. To specify all blocks use B<'*'>.
5277 The keyword B<sub> indicates a named sub. For anonymous subs, use the special
5280 For example, the following parameter specifies C<sub>, labels, C<BEGIN>, and
5283 -cscl="sub : BEGIN END"
5285 (the meaning of the -cscl parameter is described above.) Note that
5286 quotes are required around the list of block types because of the
5287 spaces. For another example, the following list specifies all block types
5288 for vertical tightness:
5292 =head2 Specifying File Extensions
5294 Several parameters allow default file extensions to be overridden. For
5295 example, a backup file extension may be specified with B<-bext=ext>,
5296 where B<ext> is some new extension. In order to provides the user some
5297 flexibility, the following convention is used in all cases to decide if
5298 a leading '.' should be used. If the extension C<ext> begins with
5299 C<A-Z>, C<a-z>, or C<0-9>, then it will be appended to the filename with
5300 an intermediate '.' (or perhaps a '_' on VMS systems). Otherwise, it
5301 will be appended directly.
5303 For example, suppose the file is F<somefile.pl>. For C<-bext=old>, a '.' is
5304 added to give F<somefile.pl.old>. For C<-bext=.old>, no additional '.' is
5305 added, so again the backup file is F<somefile.pl.old>. For C<-bext=~>, then no
5306 dot is added, and the backup file will be F<somefile.pl~> .
5308 =head1 SWITCHES WHICH MAY BE NEGATED
5310 The following list shows all short parameter names which allow a prefix
5311 'n' to produce the negated form:
5313 D anl asbl asc ast asu atc atnl aws b
5314 baa baao bar bbao bbb bbc bbs bl bli boa
5315 boc bok bol bom bos bot cblx ce conv cs
5316 csc cscb cscw dac dbc dcbl dcsc ddf dln dnl
5317 dop dp dpro drc dsc dsm dsn dtc dtt dwic
5318 dwls dwrs dws eos f fll fpva frm fs fso
5319 gcs hbc hbcm hbco hbh hbhh hbi hbj hbk hbm
5320 hbn hbp hbpd hbpu hbq hbs hbsc hbv hbw hent
5321 hic hicm hico hih hihh hii hij hik him hin
5322 hip hipd hipu hiq his hisc hiv hiw hsc html
5323 ibc icb icp iob isbc iscl kgb kgbd kgbi kis
5324 lal log lop lp lsl mem nib ohbr okw ola
5325 olc oll olq opr opt osbc osbr otr ple pod
5326 pvl q sac sbc sbl scbb schb scp scsb sct
5327 se sfp sfs skp sob sobb sohb sop sosb sot
5328 ssc st sts t tac tbc toc tp tqw trp
5329 ts tsc tso vbc vc vmll vsc w wfc wn
5332 Equivalently, the prefix 'no' or 'no-' on the corresponding long names may be
5339 =item B<Parsing Limitations>
5341 Perltidy should work properly on most perl scripts. It does a lot of
5342 self-checking, but still, it is possible that an error could be
5343 introduced and go undetected. Therefore, it is essential to make
5344 careful backups and to test reformatted scripts.
5346 The main current limitation is that perltidy does not scan modules
5347 included with 'use' statements. This makes it necessary to guess the
5348 context of any bare words introduced by such modules. Perltidy has good
5349 guessing algorithms, but they are not infallible. When it must guess,
5350 it leaves a message in the log file.
5352 If you encounter a bug, please report it.
5354 =item B<What perltidy does not parse and format>
5356 Perltidy indents but does not reformat comments and C<qw> quotes.
5357 Perltidy does not in any way modify the contents of here documents or
5358 quoted text, even if they contain source code. (You could, however,
5359 reformat them separately). Perltidy does not format 'format' sections
5360 in any way. And, of course, it does not modify pod documents.
5368 =item B<Temporary files>
5370 Under the -html option with the default --pod2html flag, a temporary file is
5371 required to pass text to Pod::Html. Unix systems will try to use the POSIX
5372 tmpnam() function. Otherwise the file F<perltidy.TMP> will be temporarily
5373 created in the current working directory.
5375 =item B<Special files when standard input is used>
5377 When standard input is used, the log file, if saved, is F<perltidy.LOG>,
5378 and any errors are written to F<perltidy.ERR> unless the B<-se> flag is
5379 set. These are saved in the current working directory.
5381 =item B<Files overwritten>
5383 The following file extensions are used by perltidy, and files with these
5384 extensions may be overwritten or deleted: F<.ERR>, F<.LOG>, F<.TEE>,
5385 and/or F<.tdy>, F<.html>, and F<.bak>, depending on the run type and
5388 =item B<Files extensions limitations>
5390 Perltidy does not operate on files for which the run could produce a file with
5391 a duplicated file extension. These extensions include F<.LOG>, F<.ERR>,
5392 F<.TEE>, and perhaps F<.tdy> and F<.bak>, depending on the run type. The
5393 purpose of this rule is to prevent generating confusing filenames such as
5394 F<somefile.tdy.tdy.tdy>.
5398 =head1 ERROR HANDLING
5400 An exit value of 0, 1, or 2 is returned by perltidy to indicate the status of the result.
5402 A exit value of 0 indicates that perltidy ran to completion with no error messages.
5404 A non-zero exit value indicates some kind of problem was detected.
5406 An exit value of 1 indicates that perltidy terminated prematurely, usually due
5407 to some kind of errors in the input parameters. This can happen for example if
5408 a parameter is misspelled or given an invalid value. Error messages in the
5409 standard error output will indicate the cause of any problem. If perltidy
5410 terminates prematurely then no output files will be produced.
5412 An exit value of 2 indicates that perltidy was able to run to completion but
5413 there there are (1) warning messages in the standard error output related to
5414 parameter errors or problems and/or (2) warning messages in the perltidy error
5415 file(s) relating to possible syntax errors in one or more of the source
5416 script(s) being tidied. When multiple files are being processed, an error
5417 detected in any single file will produce this type of exit condition.
5421 perlstyle(1), Perl::Tidy(3)
5425 The perltidy binary uses the Perl::Tidy module and is installed when that module is installed. The module name is case-sensitive. For example, the basic command for installing with cpanm is 'cpanm Perl::Tidy'.
5429 This man page documents perltidy version 20221112
5433 The source code repository is at L<https://github.com/perltidy/perltidy>.
5435 To report a new bug or problem, use the "issues" link on this page.
5439 Copyright (c) 2000-2022 by Steve Hancock
5443 This package is free software; you can redistribute it and/or modify it
5444 under the terms of the "GNU General Public License".
5446 Please refer to the file "COPYING" for details.
5450 This package is distributed in the hope that it will be useful,
5451 but WITHOUT ANY WARRANTY; without even the implied warranty of
5452 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5454 See the "GNU General Public License" for more details.