1PERLTIDY(1) User Contributed Perl Documentation PERLTIDY(1)
2
3
4
6 perltidy - a perl script indenter and reformatter
7
9 perltidy [ options ] file1 file2 file3 ...
10 (output goes to file1.tdy, file2.tdy, file3.tdy, ...)
11 perltidy [ options ] file1 -o outfile
12 perltidy [ options ] file1 -st >outfile
13 perltidy [ options ] <infile >outfile
14
16 Perltidy reads a perl script and writes an indented, reformatted
17 script. The formatting process involves converting the script into a
18 string of tokens, removing any non-essential whitespace, and then
19 rewriting the string of tokens with whitespace using whatever rules are
20 specified, or defaults. This happens in a series of operations which
21 can be controlled with the parameters described in this document.
22
23 Perltidy is a commandline frontend to the module Perl::Tidy. For
24 documentation describing how to call the Perl::Tidy module from other
25 applications see the separate documentation for Perl::Tidy. It is the
26 file Perl::Tidy.pod in the source distribution.
27
28 Many users will find enough information in "EXAMPLES" to get started.
29 New users may benefit from the short tutorial which can be found at
30 http://perltidy.sourceforge.net/tutorial.html
31
32 A convenient aid to systematically defining a set of style parameters
33 can be found at http://perltidy.sourceforge.net/stylekey.html
34
35 Perltidy can produce output on either of two modes, depending on the
36 existence of an -html flag. Without this flag, the output is passed
37 through a formatter. The default formatting tries to follow the
38 recommendations in perlstyle(1), but it can be controlled in detail
39 with numerous input parameters, which are described in "FORMATTING
40 OPTIONS".
41
42 When the -html flag is given, the output is passed through an HTML
43 formatter which is described in "HTML OPTIONS".
44
46 perltidy somefile.pl
47
48 This will produce a file somefile.pl.tdy containing the script
49 reformatted using the default options, which approximate the style
50 suggested in perlstyle(1). The source file somefile.pl is unchanged.
51
52 perltidy *.pl
53
54 Execute perltidy on all .pl files in the current directory with the
55 default options. The output will be in files with an appended .tdy
56 extension. For any file with an error, there will be a file with
57 extension .ERR.
58
59 perltidy -b file1.pl file2.pl
60
61 Modify file1.pl and file2.pl in place, and backup the originals to
62 file1.pl.bak and file2.pl.bak. If file1.pl.bak and/or file2.pl.bak
63 already exist, they will be overwritten.
64
65 perltidy -b -bext='/' file1.pl file2.pl
66
67 Same as the previous example except that the backup files file1.pl.bak
68 and file2.pl.bak will be deleted if there are no errors.
69
70 perltidy -gnu somefile.pl
71
72 Execute perltidy on file somefile.pl with a style which approximates
73 the GNU Coding Standards for C programs. The output will be
74 somefile.pl.tdy.
75
76 perltidy -i=3 somefile.pl
77
78 Execute perltidy on file somefile.pl, with 3 columns for each level of
79 indentation (-i=3) instead of the default 4 columns. There will not be
80 any tabs in the reformatted script, except for any which already exist
81 in comments, pod documents, quotes, and here documents. Output will be
82 somefile.pl.tdy.
83
84 perltidy -i=3 -et=8 somefile.pl
85
86 Same as the previous example, except that leading whitespace will be
87 entabbed with one tab character per 8 spaces.
88
89 perltidy -ce -l=72 somefile.pl
90
91 Execute perltidy on file somefile.pl with all defaults except use
92 "cuddled elses" (-ce) and a maximum line length of 72 columns (-l=72)
93 instead of the default 80 columns.
94
95 perltidy -g somefile.pl
96
97 Execute perltidy on file somefile.pl and save a log file
98 somefile.pl.LOG which shows the nesting of braces, parentheses, and
99 square brackets at the start of every line.
100
101 perltidy -html somefile.pl
102
103 This will produce a file somefile.pl.html containing the script with
104 html markup. The output file will contain an embedded style sheet in
105 the <HEAD> section which may be edited to change the appearance.
106
107 perltidy -html -css=mystyle.css somefile.pl
108
109 This will produce a file somefile.pl.html containing the script with
110 html markup. This output file will contain a link to a separate style
111 sheet file mystyle.css. If the file mystyle.css does not exist, it
112 will be created. If it exists, it will not be overwritten.
113
114 perltidy -html -pre somefile.pl
115
116 Write an html snippet with only the PRE section to somefile.pl.html.
117 This is useful when code snippets are being formatted for inclusion in
118 a larger web page. No style sheet will be written in this case.
119
120 perltidy -html -ss >mystyle.css
121
122 Write a style sheet to mystyle.css and exit.
123
124 perltidy -html -frm mymodule.pm
125
126 Write html with a frame holding a table of contents and the source
127 code. The output files will be mymodule.pm.html (the frame),
128 mymodule.pm.toc.html (the table of contents), and mymodule.pm.src.html
129 (the source code).
130
132 The entire command line is scanned for options, and they are processed
133 before any files are processed. As a result, it does not matter
134 whether flags are before or after any filenames. However, the relative
135 order of parameters is important, with later parameters overriding the
136 values of earlier parameters.
137
138 For each parameter, there is a long name and a short name. The short
139 names are convenient for keyboard input, while the long names are self-
140 documenting and therefore useful in scripts. It is customary to use
141 two leading dashes for long names, but one may be used.
142
143 Most parameters which serve as on/off flags can be negated with a
144 leading "n" (for the short name) or a leading "no" or "no-" (for the
145 long name). For example, the flag to outdent long quotes is -olq or
146 --outdent-long-quotes. The flag to skip this is -nolq or
147 --nooutdent-long-quotes or --no-outdent-long-quotes.
148
149 Options may not be bundled together. In other words, options -q and -g
150 may NOT be entered as -qg.
151
152 Option names may be terminated early as long as they are uniquely
153 identified. For example, instead of --dump-token-types, it would be
154 sufficient to enter --dump-tok, or even --dump-t, to uniquely identify
155 this command.
156
157 I/O Control
158 The following parameters concern the files which are read and written.
159
160 -h, --help
161 Show summary of usage and exit.
162
163 -o=filename, --outfile=filename
164 Name of the output file (only if a single input file is being
165 processed). If no output file is specified, and output is not
166 redirected to the standard output (see -st), the output will go to
167 filename.tdy. [Note: - does not redirect to standard output. Use
168 -st instead.]
169
170 -st, --standard-output
171 Perltidy must be able to operate on an arbitrarily large number of
172 files in a single run, with each output being directed to a
173 different output file. Obviously this would conflict with
174 outputting to the single standard output device, so a special flag,
175 -st, is required to request outputting to the standard output. For
176 example,
177
178 perltidy somefile.pl -st >somefile.new.pl
179
180 This option may only be used if there is just a single input file.
181 The default is -nst or --nostandard-output.
182
183 -se, --standard-error-output
184 If perltidy detects an error when processing file somefile.pl, its
185 default behavior is to write error messages to file
186 somefile.pl.ERR. Use -se to cause all error messages to be sent to
187 the standard error output stream instead. This directive may be
188 negated with -nse. Thus, you may place -se in a .perltidyrc and
189 override it when desired with -nse on the command line.
190
191 -oext=ext, --output-file-extension=ext
192 Change the extension of the output file to be ext instead of the
193 default tdy (or html in case the --html option is used). See
194 "Specifying File Extensions".
195
196 -opath=path, --output-path=path
197 When perltidy creates a filename for an output file, by default it
198 merely appends an extension to the path and basename of the input
199 file. This parameter causes the path to be changed to path
200 instead.
201
202 The path should end in a valid path separator character, but
203 perltidy will try to add one if it is missing.
204
205 For example
206
207 perltidy somefile.pl -opath=/tmp/
208
209 will produce /tmp/somefile.pl.tdy. Otherwise, somefile.pl.tdy will
210 appear in whatever directory contains somefile.pl.
211
212 If the path contains spaces, it should be placed in quotes.
213
214 This parameter will be ignored if output is being directed to
215 standard output, or if it is being specified explicitly with the
216 -o=s parameter.
217
218 -b, --backup-and-modify-in-place
219 Modify the input file or files in-place and save the original with
220 the extension .bak. Any existing .bak file will be deleted. See
221 next item for changing the default backup extension, and for
222 eliminating the backup file altogether.
223
224 Please Note: Writing back to the input file increases the risk of
225 data loss or corruption in the event of a software or hardware
226 malfunction. Before using the -b parameter please be sure to have
227 backups and verify that it works correctly in your environment and
228 operating system.
229
230 A -b flag will be ignored if input is from standard input or goes
231 to standard output, or if the -html flag is set.
232
233 In particular, if you want to use both the -b flag and the -pbp
234 (--perl-best-practices) flag, then you must put a -nst flag after
235 the -pbp flag because it contains a -st flag as one of its
236 components, which means that output will go to the standard output
237 stream.
238
239 -bext=ext, --backup-file-extension=ext
240 This parameter serves two purposes: (1) to change the extension of
241 the backup file to be something other than the default .bak, and
242 (2) to indicate that no backup file should be saved.
243
244 To change the default extension to something other than .bak see
245 "Specifying File Extensions".
246
247 A backup file of the source is always written, but you can request
248 that it be deleted at the end of processing if there were no
249 errors. This is risky unless the source code is being maintained
250 with a source code control system.
251
252 To indicate that the backup should be deleted include one forward
253 slash, /, in the extension. If any text remains after the slash is
254 removed it will be used to define the backup file extension (which
255 is always created and only deleted if there were no errors).
256
257 Here are some examples:
258
259 Parameter Extension Backup File Treatment
260 <-bext=bak> F<.bak> Keep (same as the default behavior)
261 <-bext='/'> F<.bak> Delete if no errors
262 <-bext='/backup'> F<.backup> Delete if no errors
263 <-bext='original/'> F<.original> Delete if no errors
264
265 -bm=s, --backup-method=s
266 This parameter should not normally be used but is available in the
267 event that problems arise as a transition is made from an older
268 implementation of the backup logic to a newer implementation. The
269 newer implementation is the default and is specified with
270 -bm='copy'. The older implementation is specified with -bm='move'.
271 The difference is that the older implementation made the backup by
272 moving the input file to the backup file, and the newer
273 implementation makes the backup by copying the input file. The
274 newer implementation preserves the file system inode value. This
275 may avoid problems with other software running simultaneously.
276 This change was made as part of issue git #103 at github.
277
278 -w, --warning-output
279 Setting -w causes any non-critical warning messages to be reported
280 as errors. These include messages about possible pod problems,
281 possibly bad starting indentation level, and cautions about
282 indirect object usage. The default, -nw or --nowarning-output, is
283 not to include these warnings.
284
285 -q, --quiet
286 Deactivate error messages (for running under an editor).
287
288 For example, if you use a vi-style editor, such as vim, you may
289 execute perltidy as a filter from within the editor using something
290 like
291
292 :n1,n2!perltidy -q
293
294 where "n1,n2" represents the selected text. Without the -q flag,
295 any error message may mess up your screen, so be prepared to use
296 your "undo" key.
297
298 -log, --logfile
299 Save the .LOG file, which has many useful diagnostics. Perltidy
300 always creates a .LOG file, but by default it is deleted unless a
301 program bug is suspected. Setting the -log flag forces the log
302 file to be saved.
303
304 -g=n, --logfile-gap=n
305 Set maximum interval between input code lines in the logfile. This
306 purpose of this flag is to assist in debugging nesting errors. The
307 value of "n" is optional. If you set the flag -g without the value
308 of "n", it will be taken to be 1, meaning that every line will be
309 written to the log file. This can be helpful if you are looking
310 for a brace, paren, or bracket nesting error.
311
312 Setting -g also causes the logfile to be saved, so it is not
313 necessary to also include -log.
314
315 If no -g flag is given, a value of 50 will be used, meaning that at
316 least every 50th line will be recorded in the logfile. This helps
317 prevent excessively long log files.
318
319 Setting a negative value of "n" is the same as not setting -g at
320 all.
321
322 -npro --noprofile
323 Ignore any .perltidyrc command file. Normally, perltidy looks
324 first in your current directory for a .perltidyrc file of
325 parameters. (The format is described below). If it finds one, it
326 applies those options to the initial default values, and then it
327 applies any that have been defined on the command line. If no
328 .perltidyrc file is found, it looks for one in your home directory.
329
330 If you set the -npro flag, perltidy will not look for this file.
331
332 -pro=filename or --profile=filename
333 To simplify testing and switching .perltidyrc files, this command
334 may be used to specify a configuration file which will override the
335 default name of .perltidyrc. There must not be a space on either
336 side of the '=' sign. For example, the line
337
338 perltidy -pro=testcfg
339
340 would cause file testcfg to be used instead of the default
341 .perltidyrc.
342
343 A pathname begins with three dots, e.g. ".../.perltidyrc",
344 indicates that the file should be searched for starting in the
345 current directory and working upwards. This makes it easier to have
346 multiple projects each with their own .perltidyrc in their root
347 directories.
348
349 -opt, --show-options
350 Write a list of all options used to the .LOG file. Please see
351 --dump-options for a simpler way to do this.
352
353 -f, --force-read-binary
354 Force perltidy to process binary files. To avoid producing
355 excessive error messages, perltidy skips files identified by the
356 system as non-text. However, valid perl scripts containing binary
357 data may sometimes be identified as non-text, and this flag forces
358 perltidy to process them.
359
360 -ast, --assert-tidy
361 This flag asserts that the input and output code streams are
362 identical, or in other words that the input code is already 'tidy'
363 according to the formatting parameters. If this is not the case,
364 an error message noting this is produced. This error message will
365 cause the process to return a non-zero exit code. The test for
366 this is made by comparing an MD5 hash value for the input and
367 output code streams. This flag has no other effect on the
368 functioning of perltidy. This might be useful for certain code
369 maintenance operations. Note: you will not see this message if you
370 have error messages turned off with the -quiet flag.
371
372 -asu, --assert-untidy
373 This flag asserts that the input and output code streams are
374 different, or in other words that the input code is 'untidy'
375 according to the formatting parameters. If this is not the case,
376 an error message noting this is produced. This flag has no other
377 effect on the functioning of perltidy.
378
380 Basic Options
381 --notidy
382 This flag disables all formatting and causes the input to be copied
383 unchanged to the output except for possible changes in line ending
384 characters and any pre- and post-filters. This can be useful in
385 conjunction with a hierarchical set of .perltidyrc files to avoid
386 unwanted code tidying. See also "Skipping Selected Sections of
387 Code" for a way to avoid tidying specific sections of code.
388
389 -i=n, --indent-columns=n
390 Use n columns per indentation level (default n=4).
391
392 -l=n, --maximum-line-length=n
393 The default maximum line length is n=80 characters. Perltidy will
394 try to find line break points to keep lines below this length.
395 However, long quotes and side comments may cause lines to exceed
396 this length.
397
398 The default length of 80 comes from the past when this was the
399 standard CRT screen width. Many programmers prefer to increase
400 this to something like 120.
401
402 Setting -l=0 is equivalent to setting -l=(a very large number).
403 But this is not recommended because, for example, a very long list
404 will be formatted in a single long line.
405
406 -vmll, --variable-maximum-line-length
407 A problem arises using a fixed maximum line length with very deeply
408 nested code and data structures because eventually the amount of
409 leading whitespace used for indicating indentation takes up most or
410 all of the available line width, leaving little or no space for the
411 actual code or data. One solution is to use a very long line
412 length. Another solution is to use the -vmll flag, which basically
413 tells perltidy to ignore leading whitespace when measuring the line
414 length.
415
416 To be precise, when the -vmll parameter is set, the maximum line
417 length of a line of code will be M+L*I, where
418
419 M is the value of --maximum-line-length=M (-l=M), default 80,
420 I is the value of --indent-columns=I (-i=I), default 4,
421 L is the indentation level of the line of code
422
423 When this flag is set, the choice of breakpoints for a block of
424 code should be essentially independent of its nesting depth.
425 However, the absolute line lengths, including leading whitespace,
426 can still be arbitrarily large. This problem can be avoided by
427 including the next parameter.
428
429 The default is not to do this (-nvmll).
430
431 -wc=n, --whitespace-cycle=n
432 This flag also addresses problems with very deeply nested code and
433 data structures. When the nesting depth exceeds the value n the
434 leading whitespace will be reduced and start at a depth of 1 again.
435 The result is that blocks of code will shift back to the left
436 rather than moving arbitrarily far to the right. This occurs
437 cyclically to any depth.
438
439 For example if one level of indentation equals 4 spaces (-i=4, the
440 default), and one uses -wc=15, then if the leading whitespace on a
441 line exceeds about 4*15=60 spaces it will be reduced back to 4*1=4
442 spaces and continue increasing from there. If the whitespace never
443 exceeds this limit the formatting remains unchanged.
444
445 The combination of -vmll and -wc=n provides a solution to the
446 problem of displaying arbitrarily deep data structures and code in
447 a finite window, although -wc=n may of course be used without
448 -vmll.
449
450 The default is not to use this, which can also be indicated using
451 -wc=0.
452
453 Tabs
454 Using tab characters will almost certainly lead to future
455 portability and maintenance problems, so the default and
456 recommendation is not to use them. For those who prefer tabs,
457 however, there are two different options.
458
459 Except for possibly introducing tab indentation characters, as
460 outlined below, perltidy does not introduce any tab characters into
461 your file, and it removes any tabs from the code (unless requested
462 not to do so with -fws). If you have any tabs in your comments,
463 quotes, or here-documents, they will remain.
464
465 -et=n, --entab-leading-whitespace
466 This flag causes each n leading space characters produced by
467 the formatting process to be replaced by one tab character.
468 The formatting process itself works with space characters. The
469 -et=n parameter is applied as a last step, after formatting is
470 complete, to convert leading spaces into tabs. Before starting
471 to use tabs, it is essential to first get the indentation
472 controls set as desired without tabs, particularly the two
473 parameters --indent-columns=n (or -i=n) and
474 --continuation-indentation=n (or -ci=n).
475
476 The value of the integer n can be any value but can be
477 coordinated with the number of spaces used for indentation. For
478 example, -et=4 -ci=4 -i=4 will produce one tab for each
479 indentation level and and one for each continuation indentation
480 level. You may want to coordinate the value of n with what
481 your display software assumes for the spacing of a tab.
482
483 -t, --tabs
484 This flag causes one leading tab character to be inserted for
485 each level of indentation. Certain other features are
486 incompatible with this option, and if these options are also
487 given, then a warning message will be issued and this flag will
488 be unset. One example is the -lp option. This flag is retained
489 for backwards compatibility, but if you use tabs, the -et=n
490 flag is recommended. If both -t and -et=n are set, the -et=n
491 is used.
492
493 -dt=n, --default-tabsize=n
494 If the first line of code passed to perltidy contains leading
495 tabs but no tab scheme is specified for the output stream then
496 perltidy must guess how many spaces correspond to each leading
497 tab. This number of spaces n corresponding to each leading tab
498 of the input stream may be specified with -dt=n. The default
499 is n=8.
500
501 This flag has no effect if a tab scheme is specified for the
502 output stream, because then the input stream is assumed to use
503 the same tab scheme and indentation spaces as for the output
504 stream (any other assumption would lead to unstable editing).
505
506 -io, --indent-only
507 This flag is used to deactivate all whitespace and line break
508 changes within non-blank lines of code. When it is in effect, the
509 only change to the script will be to the indentation and to the
510 number of blank lines. And any flags controlling whitespace and
511 newlines will be ignored. You might want to use this if you are
512 perfectly happy with your whitespace and line breaks, and merely
513 want perltidy to handle the indentation. (This also speeds up
514 perltidy by well over a factor of two, so it might be useful when
515 perltidy is merely being used to help find a brace error in a large
516 script).
517
518 Setting this flag is equivalent to setting --freeze-newlines and
519 --freeze-whitespace.
520
521 If you also want to keep your existing blank lines exactly as they
522 are, you can add --freeze-blank-lines.
523
524 With this option perltidy is still free to modify the indenting
525 (and outdenting) of code and comments as it normally would. If you
526 also want to prevent long comment lines from being outdented, you
527 can add either -noll or -l=0.
528
529 Setting this flag will prevent perltidy from doing any special
530 operations on closing side comments. You may still delete all side
531 comments however when this flag is in effect.
532
533 -enc=s, --character-encoding=s
534 This flag indicates if the input data stream uses a character
535 encoding. Perltidy does not look for the encoding directives in
536 the source stream, such as use utf8, and instead relies on this
537 flag to determine the encoding. (This is because perltidy often
538 works on snippets of code rather than complete files, so it cannot
539 rely on use utf8 directives). Consequently perltidy is likely to
540 encounter problems formatting a file which is only partially
541 encoded.
542
543 The possible values for s are:
544
545 -enc=none if no encoding is used, or
546 -enc=utf8 for encoding in utf8
547 -enc=guess if perltidy should guess between these two possibilities.
548
549 The value none causes the stream to be processed without special
550 encoding assumptions. This is appropriate for files which are
551 written in single-byte character encodings such as latin-1.
552
553 The value utf8 causes the stream to be read and written as UTF-8.
554 If the input stream cannot be decoded with this encoding then
555 processing is not done.
556
557 The value guess tells perltidy to guess between either utf8
558 encoding or no encoding (meaning one character per byte). The
559 guess option uses the Encode::Guess module which has been found to
560 be reliable at detecting if a file is encoded in utf8 or not.
561
562 The current default is guess.
563
564 The abbreviations -utf8 or -UTF8 are equivalent to -enc=utf8, and
565 the abbreviation -guess is equivalent to -enc=guess. So to process
566 a file named file.pl which is encoded in UTF-8 you can use:
567
568 perltidy -utf8 file.pl
569
570 or
571
572 perltidy -guess file.pl
573
574 or simply
575
576 perltidy file.pl
577
578 since -guess is the default.
579
580 To process files with an encoding other than UTF-8, it would be
581 necessary to write a short program which calls the Perl::Tidy
582 module with some pre- and post-processing to handle decoding and
583 encoding.
584
585 -eos=s, --encode-output-strings=s
586 This flag was added to resolve an issue involving the interface
587 between Perl::Tidy and calling programs, and in particular
588 Code::TidyAll (tidyall).
589
590 If you only run the perltidy binary this flag has no effect. If
591 you run a program which calls the Perl::Tidy module and receives a
592 string in return, then the meaning of the flag is as follows:
593
594 • The setting -eos means Perl::Tidy should encode any string
595 which it decodes. This is the default because it makes
596 perltidy behave well as a filter, and is the correct setting
597 for most programs.
598
599 • The setting -neos means that a string should remain decoded if
600 it was decoded by Perl::Tidy. This is only appropriate if the
601 calling program will handle any needed encoding before
602 outputting the string.
603
604 The default was changed from -neos to -eos in versions after
605 20220217. If this change causes a program to start running
606 incorrectly on encoded files, an emergency fix might be to set
607 -neos. Additional information can be found in the man pages for
608 the Perl::Tidy module and also in
609 <https://github.com/perltidy/perltidy/blob/master/docs/eos_flag.md>.
610
611 -gcs, --use-unicode-gcstring
612 This flag controls whether or not perltidy may use module
613 Unicode::GCString to obtain accurate display widths of wide
614 characters. The default is --nouse-unicode-gcstring.
615
616 If this flag is set, and text is encoded, perltidy will look for
617 the module Unicode::GCString and, if found, will use it to obtain
618 character display widths. This can improve displayed vertical
619 alignment for files with wide characters. It is a nice feature but
620 it is off by default to avoid conflicting formatting when there are
621 multiple developers. Perltidy installation does not require
622 Unicode::GCString, so users wanting to use this feature need set
623 this flag and also to install Unicode::GCString separately.
624
625 If this flag is set and perltidy does not find module
626 Unicode::GCString, a warning message will be produced and
627 processing will continue but without the potential benefit provided
628 by the module.
629
630 Also note that actual vertical alignment depends upon the fonts
631 used by the text display software, so vertical alignment may not be
632 optimal even when Unicode::GCString is used.
633
634 -ole=s, --output-line-ending=s
635 where s="win", "dos", "unix", or "mac". This flag tells perltidy
636 to output line endings for a specific system. Normally, perltidy
637 writes files with the line separator character of the host system.
638 The "win" and "dos" flags have an identical result.
639
640 -ple, --preserve-line-endings
641 This flag tells perltidy to write its output files with the same
642 line endings as the input file, if possible. It should work for
643 dos, unix, and mac line endings. It will only work if perltidy
644 input comes from a filename (rather than stdin, for example). If
645 perltidy has trouble determining the input file line ending, it
646 will revert to the default behavior of using the line ending of the
647 host system.
648
649 -atnl, --add-terminal-newline
650 This flag, which is enabled by default, allows perltidy to
651 terminate the last line of the output stream with a newline
652 character, regardless of whether or not the input stream was
653 terminated with a newline character. If this flag is negated, with
654 -natnl, then perltidy will add a terminal newline to the the output
655 stream only if the input stream is terminated with a newline.
656
657 Negating this flag may be useful for manipulating one-line scripts
658 intended for use on a command line.
659
660 -it=n, --iterations=n
661 This flag causes perltidy to do n complete iterations. The reason
662 for this flag is that code beautification is an iterative process
663 and in some cases the output from perltidy can be different if it
664 is applied a second time. For most purposes the default of n=1
665 should be satisfactory. However n=2 can be useful when a major
666 style change is being made, or when code is being beautified on
667 check-in to a source code control system. It has been found to be
668 extremely rare for the output to change after 2 iterations. If a
669 value n is greater than 2 is input then a convergence test will be
670 used to stop the iterations as soon as possible, almost always
671 after 2 iterations. See the next item for a simplified iteration
672 control.
673
674 This flag has no effect when perltidy is used to generate html.
675
676 -conv, --converge
677 This flag is equivalent to -it=4 and is included to simplify
678 iteration control. For all practical purposes one either does or
679 does not want to be sure that the output is converged, and there is
680 no penalty to using a large iteration limit since perltidy will
681 check for convergence and stop iterating as soon as possible. The
682 default is -nconv (no convergence check). Using -conv will
683 approximately double run time since typically one extra iteration
684 is required to verify convergence. No extra iterations are
685 required if no new line breaks are made, and two extra iterations
686 are occasionally needed when reformatting complex code structures,
687 such as deeply nested ternary statements.
688
689 Code Indentation Control
690 -ci=n, --continuation-indentation=n
691 Continuation indentation is extra indentation spaces applied when a
692 long line is broken. The default is n=2, illustrated here:
693
694 my $level = # -ci=2
695 ( $max_index_to_go >= 0 ) ? $levels_to_go[0] : $last_output_level;
696
697 The same example, with n=0, is a little harder to read:
698
699 my $level = # -ci=0
700 ( $max_index_to_go >= 0 ) ? $levels_to_go[0] : $last_output_level;
701
702 The value given to -ci is also used by some commands when a small
703 space is required. Examples are commands for outdenting labels,
704 -ola, and control keywords, -okw.
705
706 When default values are not used, it is recommended that either
707
708 (1) the value n given with -ci=n be no more than about one-half of
709 the number of spaces assigned to a full indentation level on the
710 -i=n command, or
711
712 (2) the flag -extended-continuation-indentation is used (see next
713 section).
714
715 -xci, --extended-continuation-indentation
716 This flag allows perltidy to use some improvements which have been
717 made to its indentation model. One of the things it does is
718 "extend" continuation indentation deeper into structures, hence the
719 name. The improved indentation is particularly noticeable when the
720 flags -ci=n and -i=n use the same value of n. There are no
721 significant disadvantages to using this flag, but to avoid
722 disturbing existing formatting the default is not to use it, -nxci.
723
724 Please see the section "-pbp, --perl-best-practices" for an example
725 of how this flag can improve the formatting of ternary statements.
726 It can also improve indentation of some multi-line qw lists as
727 shown below.
728
729 # perltidy
730 foreach $color (
731 qw(
732 AntiqueWhite3 Bisque1 Bisque2 Bisque3 Bisque4
733 SlateBlue3 RoyalBlue1 SteelBlue2 DeepSkyBlue3
734 ),
735 qw(
736 LightBlue1 DarkSlateGray1 Aquamarine2 DarkSeaGreen2
737 SeaGreen1 Yellow1 IndianRed1 IndianRed2 Tan1 Tan4
738 )
739 )
740
741 # perltidy -xci
742 foreach $color (
743 qw(
744 AntiqueWhite3 Bisque1 Bisque2 Bisque3 Bisque4
745 SlateBlue3 RoyalBlue1 SteelBlue2 DeepSkyBlue3
746 ),
747 qw(
748 LightBlue1 DarkSlateGray1 Aquamarine2 DarkSeaGreen2
749 SeaGreen1 Yellow1 IndianRed1 IndianRed2 Tan1 Tan4
750 )
751 )
752
753 -sil=n --starting-indentation-level=n
754 By default, perltidy examines the input file and tries to determine
755 the starting indentation level. While it is often zero, it may not
756 be zero for a code snippet being sent from an editing session.
757
758 To guess the starting indentation level perltidy simply assumes
759 that indentation scheme used to create the code snippet is the same
760 as is being used for the current perltidy process. This is the
761 only sensible guess that can be made. It should be correct if this
762 is true, but otherwise it probably won't. For example, if the
763 input script was written with -i=2 and the current perltidy flags
764 have -i=4, the wrong initial indentation will be guessed for a code
765 snippet which has non-zero initial indentation. Likewise, if an
766 entabbing scheme is used in the input script and not in the current
767 process then the guessed indentation will be wrong.
768
769 If the default method does not work correctly, or you want to
770 change the starting level, use -sil=n, to force the starting level
771 to be n.
772
773 List indentation using --line-up-parentheses, -lp or
774 --extended--line-up-parentheses , -xlp
775 These flags provide an alternative indentation method for list
776 data. The original flag for this is -lp, but it has some
777 limitations (explained below) which are avoided with the newer -xlp
778 flag. So -xlp is probably the better choice for new work, but the
779 -lp flag is retained to minimize changes to existing formatting.
780 If you enter both -lp and -xlp, then -xlp will be used.
781
782 In the default indentation method perltidy indents lists with 4
783 spaces, or whatever value is specified with -i=n. Here is a small
784 list formatted in this way:
785
786 # perltidy (default)
787 @month_of_year = (
788 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
789 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
790 );
791
792 The -lp or -xlp flags add extra indentation to cause the data to
793 begin past the opening parentheses of a sub call or list, or
794 opening square bracket of an anonymous array, or opening curly
795 brace of an anonymous hash. With this option, the above list would
796 become:
797
798 # perltidy -lp or -xlp
799 @month_of_year = (
800 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
801 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
802 );
803
804 If the available line length (see -l=n ) does not permit this much
805 space, perltidy will use less. For alternate placement of the
806 closing paren, see the next section.
807
808 These flags have no effect on code BLOCKS, such as if/then/else
809 blocks, which always use whatever is specified with -i=n.
810
811 Some limitations on these flags are:
812
813 • A limitation on -lp, but not -xlp, occurs in situations where
814 perltidy does not have complete freedom to choose line breaks.
815 Then it may temporarily revert to its default indentation
816 method. This can occur for example if there are blank lines,
817 block comments, multi-line quotes, or side comments between the
818 opening and closing parens, braces, or brackets. It will also
819 occur if a multi-line anonymous sub occurs within a container
820 since that will impose specific line breaks (such as line
821 breaks after statements).
822
823 • For both the -lp and -xlp flags, any parameter which
824 significantly restricts the ability of perltidy to choose
825 newlines will conflict with these flags and will cause them to
826 be deactivated. These include -io, -fnl, -nanl, and -ndnl.
827
828 • The -lp and -xlp options may not be used together with the -t
829 tabs option. They may, however, be used with the -et=n tab
830 method
831
832 There are some potential disadvantages of this indentation method
833 compared to the default method that should be noted:
834
835 • The available line length can quickly be used up if variable
836 names are long. This can cause deeply nested code to quickly
837 reach the line length limit, and become badly formatted, much
838 sooner than would occur with the default indentation method.
839
840 • Since the indentation depends on the lengths of variable names,
841 small changes in variable names can cause changes in
842 indentation over many lines in a file. This means that minor
843 name changes can produce significant file differences. This
844 can be annoying and does not occur with the default indentation
845 method.
846
847 Some things that can be done to minimize these problems are:
848
849 • Increase --maximum-line-length=n above the default n=80
850 characters if necessary.
851
852 • If you use -xlp then long side comments can limit the
853 indentation over multiple lines. Consider adding the flag
854 --ignore-side-comment-lengths to prevent this, or minimizing
855 the use of side comments.
856
857 • Apply this style in a limited way. By default, it applies to
858 all list containers (not just lists in parentheses). The next
859 section describes how to limit this style to, for example, just
860 function calls. The default indentation method will be applied
861 elsewhere.
862
863 -lpil=s, --line-up-parentheses-inclusion-list and -lpxl=s,
864 --line-up-parentheses-exclusion-list
865 The following discussion is written for -lp but applies equally to
866 the newer -xlp version. By default, the -lp flag applies to as
867 many containers as possible. The set of containers to which the
868 -lp style applies can be reduced by either one of these two flags:
869
870 Use -lpil=s to specify the containers to which -lp applies, or
871
872 use -lpxl=s to specify the containers to which -lp does NOT apply.
873
874 Only one of these two flags may be used. Both flags can achieve
875 the same result, but the -lpil=s flag is much easier to describe
876 and use and is recommended. The -lpxl=s flag was the original
877 implementation and is only retained for backwards compatibility.
878
879 This list s for these parameters is a string with space-separated
880 items. Each item consists of up to three pieces of information in
881 this order: (1) an optional letter code (2) a required container
882 type, and (3) an optional numeric code.
883
884 The only required piece of information is a container type, which
885 is one of '(', '[', or '{'. For example the string
886
887 -lpil='('
888
889 means use -lp formatting only on lists within parentheses, not
890 lists in square-brackets or braces. The same thing could
891 alternatively be specified with
892
893 -lpxl = '[ {'
894
895 which says to exclude lists within square-brackets and braces. So
896 what remains is lists within parentheses.
897
898 A second optional item of information which can be given for
899 parentheses is an alphanumeric letter which is used to limit the
900 selection further depending on the type of token immediately before
901 the paren. The possible letters are currently 'k', 'K', 'f', 'F',
902 'w', and 'W', with these meanings for matching whatever precedes an
903 opening paren:
904
905 'k' matches if the previous nonblank token is a perl built-in keyword (such as 'if', 'while'),
906 'K' matches if 'k' does not, meaning that the previous token is not a keyword.
907 'f' matches if the previous token is a function other than a keyword.
908 'F' matches if 'f' does not.
909 'w' matches if either 'k' or 'f' match.
910 'W' matches if 'w' does not.
911
912 For example:
913
914 -lpil = 'f('
915
916 means only apply -lp to function calls, and
917
918 -lpil = 'w('
919
920 means only apply -lp to parenthesized lists which follow a function
921 or a keyword.
922
923 This last example could alternatively be written using the -lpxl=s
924 flag as
925
926 -lpxl = '[ { W('
927
928 which says exclude -lp for lists within square-brackets, braces,
929 and parens NOT preceded by a keyword or function. Clearly, the
930 -lpil=s method is easier to understand.
931
932 An optional numeric code may follow any of the container types to
933 further refine the selection based on container contents. The
934 numeric codes are:
935
936 '0' or blank: no check on contents is made
937 '1' exclude B<-lp> unless the contents is a simple list without sublists
938 '2' exclude B<-lp> unless the contents is a simple list without sublists, without
939 code blocks, and without ternary operators
940
941 For example,
942
943 -lpil = 'f(2'
944
945 means only apply -lp to function call lists which do not contain
946 any sublists, code blocks or ternary expressions.
947
948 -cti=n, --closing-token-indentation
949 The -cti=n flag controls the indentation of a line beginning with a
950 ")", "]", or a non-block "}". Such a line receives:
951
952 -cti = 0 no extra indentation (default)
953 -cti = 1 extra indentation such that the closing token
954 aligns with its opening token.
955 -cti = 2 one extra indentation level if the line looks like:
956 ); or ]; or };
957 -cti = 3 one extra indentation level always
958
959 The flags -cti=1 and -cti=2 work well with the -lp flag (previous
960 section).
961
962 # perltidy -lp -cti=1
963 @month_of_year = (
964 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
965 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
966 );
967
968 # perltidy -lp -cti=2
969 @month_of_year = (
970 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
971 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
972 );
973
974 These flags are merely hints to the formatter and they may not
975 always be followed. In particular, if -lp is not being used, the
976 indentation for cti=1 is constrained to be no more than one
977 indentation level.
978
979 If desired, this control can be applied independently to each of
980 the closing container token types. In fact, -cti=n is merely an
981 abbreviation for -cpi=n -csbi=n -cbi=n, where: -cpi or
982 --closing-paren-indentation controls )'s, -csbi or
983 --closing-square-bracket-indentation controls ]'s, -cbi or
984 --closing-brace-indentation controls non-block }'s.
985
986 -icp, --indent-closing-paren
987 The -icp flag is equivalent to -cti=2, described in the previous
988 section. The -nicp flag is equivalent -cti=0. They are included
989 for backwards compatibility.
990
991 -icb, --indent-closing-brace
992 The -icb option gives one extra level of indentation to a brace
993 which terminates a code block . For example,
994
995 if ($task) {
996 yyy();
997 } # -icb
998 else {
999 zzz();
1000 }
1001
1002 The default is not to do this, indicated by -nicb.
1003
1004 -nib, --non-indenting-braces
1005 Normally, lines of code contained within a pair of block braces
1006 receive one additional level of indentation. This flag, which is
1007 enabled by default, causes perltidy to look for opening block
1008 braces which are followed by a special side comment. This special
1009 side comment is #<<< by default. If found, the code between this
1010 opening brace and its corresponding closing brace will not be given
1011 the normal extra indentation level. For example:
1012
1013 { #<<< a closure to contain lexical vars
1014
1015 my $var; # this line does not get one level of indentation
1016 ...
1017
1018 }
1019
1020 # this line does not 'see' $var;
1021
1022 This can be useful, for example, when combining code from different
1023 files. Different sections of code can be placed within braces to
1024 keep their lexical variables from being visible to the end of the
1025 file. To keep the new braces from causing all of their contained
1026 code to be indented if you run perltidy, and possibly introducing
1027 new line breaks in long lines, you can mark the opening braces with
1028 this special side comment.
1029
1030 Only the opening brace needs to be marked, since perltidy knows
1031 where the closing brace is. Braces contained within marked braces
1032 may also be marked as non-indenting.
1033
1034 If your code happens to have some opening braces followed by
1035 '#<<<', and you don't want this behavior, you can use -nnib to
1036 deactivate it. To make it easy to remember, the default string is
1037 the same as the string for starting a format-skipping section.
1038 There is no confusion because in that case it is for a block
1039 comment rather than a side-comment.
1040
1041 The special side comment can be changed with the next parameter.
1042
1043 -nibp=s, --non-indenting-brace-prefix=s
1044 The -nibp=string parameter may be used to change the marker for
1045 non-indenting braces. The default is equivalent to -nibp='#<<<'.
1046 The string that you enter must begin with a # and should be in
1047 quotes as necessary to get past the command shell of your system.
1048 This string is the leading text of a regex pattern that is
1049 constructed by appending pre-pending a '^' and appending a'\s', so
1050 you must also include backslashes for characters to be taken
1051 literally rather than as patterns.
1052
1053 For example, to match the side comment '#++', the parameter would
1054 be
1055
1056 -nibp='#\+\+'
1057
1058 -olq, --outdent-long-quotes
1059 When -olq is set, lines which is a quoted string longer than the
1060 value maximum-line-length will have their indentation removed to
1061 make them more readable. This is the default. To prevent such
1062 out-denting, use -nolq or --nooutdent-long-lines.
1063
1064 -oll, --outdent-long-lines
1065 This command is equivalent to --outdent-long-quotes and
1066 --outdent-long-comments, and it is included for compatibility with
1067 previous versions of perltidy. The negation of this also works,
1068 -noll or --nooutdent-long-lines, and is equivalent to setting -nolq
1069 and -nolc.
1070
1071 Outdenting Labels: -ola, --outdent-labels
1072 This command will cause labels to be outdented by 2 spaces (or
1073 whatever -ci has been set to), if possible. This is the default.
1074 For example:
1075
1076 my $i;
1077 LOOP: while ( $i = <FOTOS> ) {
1078 chomp($i);
1079 next unless $i;
1080 fixit($i);
1081 }
1082
1083 Use -nola to not outdent labels. To control line breaks after
1084 labels see "-bal=n, --break-after-labels=n".
1085
1086 Outdenting Keywords
1087 -okw, --outdent-keywords
1088 The command -okw will cause certain leading control keywords to
1089 be outdented by 2 spaces (or whatever -ci has been set to), if
1090 possible. By default, these keywords are "redo", "next",
1091 "last", "goto", and "return". The intention is to make these
1092 control keywords easier to see. To change this list of
1093 keywords being outdented, see the next section.
1094
1095 For example, using "perltidy -okw" on the previous example
1096 gives:
1097
1098 my $i;
1099 LOOP: while ( $i = <FOTOS> ) {
1100 chomp($i);
1101 next unless $i;
1102 fixit($i);
1103 }
1104
1105 The default is not to do this.
1106
1107 Specifying Outdented Keywords: -okwl=string,
1108 --outdent-keyword-list=string
1109 This command can be used to change the keywords which are
1110 outdented with the -okw command. The parameter string is a
1111 required list of perl keywords, which should be placed in
1112 quotes if there are more than one. By itself, it does not
1113 cause any outdenting to occur, so the -okw command is still
1114 required.
1115
1116 For example, the commands "-okwl="next last redo goto" -okw"
1117 will cause those four keywords to be outdented. It is probably
1118 simplest to place any -okwl command in a .perltidyrc file.
1119
1120 Whitespace Control
1121 Whitespace refers to the blank space between variables, operators, and
1122 other code tokens.
1123
1124 -fws, --freeze-whitespace
1125 This flag causes your original whitespace to remain unchanged, and
1126 causes the rest of the whitespace commands in this section, the
1127 Code Indentation section, and the Comment Control section to be
1128 ignored.
1129
1130 Tightness of curly braces, parentheses, and square brackets
1131 Here the term "tightness" will mean the closeness with which pairs
1132 of enclosing tokens, such as parentheses, contain the quantities
1133 within. A numerical value of 0, 1, or 2 defines the tightness,
1134 with 0 being least tight and 2 being most tight. Spaces within
1135 containers are always symmetric, so if there is a space after a "("
1136 then there will be a space before the corresponding ")".
1137
1138 The -pt=n or --paren-tightness=n parameter controls the space
1139 within parens. The example below shows the effect of the three
1140 possible values, 0, 1, and 2:
1141
1142 if ( ( my $len_tab = length( $tabstr ) ) > 0 ) { # -pt=0
1143 if ( ( my $len_tab = length($tabstr) ) > 0 ) { # -pt=1 (default)
1144 if ((my $len_tab = length($tabstr)) > 0) { # -pt=2
1145
1146 When n is 0, there is always a space to the right of a '(' and to
1147 the left of a ')'. For n=2 there is never a space. For n=1, the
1148 default, there is a space unless the quantity within the parens is
1149 a single token, such as an identifier or quoted string.
1150
1151 Likewise, the parameter -sbt=n or --square-bracket-tightness=n
1152 controls the space within square brackets, as illustrated below.
1153
1154 $width = $col[ $j + $k ] - $col[ $j ]; # -sbt=0
1155 $width = $col[ $j + $k ] - $col[$j]; # -sbt=1 (default)
1156 $width = $col[$j + $k] - $col[$j]; # -sbt=2
1157
1158 Curly braces which do not contain code blocks are controlled by the
1159 parameter -bt=n or --brace-tightness=n.
1160
1161 $obj->{ $parsed_sql->{ 'table' }[0] }; # -bt=0
1162 $obj->{ $parsed_sql->{'table'}[0] }; # -bt=1 (default)
1163 $obj->{$parsed_sql->{'table'}[0]}; # -bt=2
1164
1165 And finally, curly braces which contain blocks of code are
1166 controlled by the parameter -bbt=n or --block-brace-tightness=n as
1167 illustrated in the example below.
1168
1169 %bf = map { $_ => -M $_ } grep { /\.deb$/ } dirents '.'; # -bbt=0 (default)
1170 %bf = map { $_ => -M $_ } grep {/\.deb$/} dirents '.'; # -bbt=1
1171 %bf = map {$_ => -M $_} grep {/\.deb$/} dirents '.'; # -bbt=2
1172
1173 To simplify input in the case that all of the tightness flags have
1174 the same value <n>, the parameter <-act=n> or
1175 --all-containers-tightness=n is an abbreviation for the combination
1176 <-pt=n -sbt=n -bt=n -bbt=n>.
1177
1178 -xbt, --extended-block-tightness
1179 The previous section described two controls for spacing within
1180 curly braces, namely -block-brace-tightness=n for code block braces
1181 and -brace-tightness=n for all other braces.
1182
1183 There is a little fuzziness in this division of brace types though
1184 because the curly braces considered by perltidy to contain code
1185 blocks for formatting purposes, such as highlighting code
1186 structure, exclude some of the small code blocks used by Perl
1187 mainly for isolating terms. These include curly braces following a
1188 keyword where an indirect object might occur, or curly braces
1189 following a type symbol. For example, perltidy does not mark the
1190 following braces as code block braces:
1191
1192 print {*STDERR} $message;
1193 return ${$foo};
1194
1195 Consequently, the spacing within these small braced containers by
1196 default follows the flag --brace-tightness=n rather than
1197 --block-brace-tightness=n, as one might expect.
1198
1199 If desired, small blocks such as these can be made to instead
1200 follow the spacing defined by the --block-brace-tightness=n flag by
1201 setting --extended-block-tightness. The specific types of small
1202 blocks to which this parameter applies is controlled by a companion
1203 control parameter, described in the next section.
1204
1205 Note that if the two flags -bbt=n and -bt=n have the same value n
1206 then there would be no reason to set this flag.
1207
1208 -xbtl=s, --extended-block-tightness-list=s
1209 The previous parameter -xbt can be made to apply to curly braces
1210 preceded by any of the keywords
1211
1212 print printf exec system say
1213
1214 and/or the special symbols
1215
1216 $ @ % & * $#
1217
1218 The parameter string s may contain a selection of these keywords
1219 and symbols to indicate the brace types to which -xbt applies. For
1220 convenience, all of the keywords can be selected with 'k', and all
1221 of the special symbols can be selected with 't'. The default is
1222 equivalent to -xbtl='k', which selects all of the keywords.
1223
1224 Examples:
1225
1226 -xbtl='k' # selects just the keywords [DEFAULT]
1227 -xbtl="t" # selects just the special type symbols
1228 -xbtl="k t" # selects all keywords and symbols, or more simply
1229 -xbtl="kt" # selects all keywords and symbols
1230 -xbtl="print say" # selects just keywords B<print> and B<say>:
1231
1232 Here are some formatting examples using the default values of -bt=n
1233 and -bbt=n. Note that in these examples $ref is in block braces but
1234 $key is not.
1235
1236 # default formatting
1237 print {*STDERR} $message;
1238 my $val = ${$ref}{$key};
1239
1240 # perltidy -xbt or
1241 # perltidy -xbt -xbtl=k
1242 print { *STDERR } $message;
1243 my $val = ${$ref}{$key};
1244
1245 # perltidy -xbt -xbtl=t
1246 print {*STDERR} $message;
1247 my $val = ${ $ref }{$key};
1248
1249 # perltidy -xbt -xbtl=kt
1250 print { *STDERR } $message;
1251 my $val = ${ $ref }{$key};
1252
1253 Finally, note that this parameter merely changes the way that the
1254 parameter --extended-block-tightness works. It has no effect unless
1255 --extended-block-tightness is actually set.
1256
1257 -tso, --tight-secret-operators
1258 The flag -tso causes certain perl token sequences (secret
1259 operators) which might be considered to be a single operator to be
1260 formatted "tightly" (without spaces). The operators currently
1261 modified by this flag are:
1262
1263 0+ +0 ()x!! ~~<> ,=> =( )=
1264
1265 For example the sequence 0 +, which converts a string to a number,
1266 would be formatted without a space: 0+ when the -tso flag is set.
1267 This flag is off by default.
1268
1269 -sts, --space-terminal-semicolon
1270 Some programmers prefer a space before all terminal semicolons.
1271 The default is for no such space, and is indicated with -nsts or
1272 --nospace-terminal-semicolon.
1273
1274 $i = 1 ; # -sts
1275 $i = 1; # -nsts (default)
1276
1277 -sfs, --space-for-semicolon
1278 Semicolons within for loops may sometimes be hard to see,
1279 particularly when commas are also present. This option places
1280 spaces on both sides of these special semicolons, and is the
1281 default. Use -nsfs or --nospace-for-semicolon to deactivate it.
1282
1283 for ( @a = @$ap, $u = shift @a ; @a ; $u = $v ) { # -sfs (default)
1284 for ( @a = @$ap, $u = shift @a; @a; $u = $v ) { # -nsfs
1285
1286 -asc, --add-semicolons
1287 Setting -asc allows perltidy to add any missing optional semicolon
1288 at the end of a line which is followed by a closing curly brace on
1289 the next line. This is the default, and may be deactivated with
1290 -nasc or --noadd-semicolons.
1291
1292 -dsm, --delete-semicolons
1293 Setting -dsm allows perltidy to delete extra semicolons which are
1294 simply empty statements. This is the default, and may be
1295 deactivated with -ndsm or --nodelete-semicolons. (Such semicolons
1296 are not deleted, however, if they would promote a side comment to a
1297 block comment).
1298
1299 -aws, --add-whitespace
1300 Setting this option allows perltidy to add certain whitespace to
1301 improve code readability. This is the default. If you do not want
1302 any whitespace added, but are willing to have some whitespace
1303 deleted, use -naws. (Use -fws to leave whitespace completely
1304 unchanged).
1305
1306 -dws, --delete-old-whitespace
1307 Setting this option allows perltidy to remove some old whitespace
1308 between characters, if necessary. This is the default. If you do
1309 not want any old whitespace removed, use -ndws or
1310 --nodelete-old-whitespace.
1311
1312 Detailed whitespace controls around tokens
1313 For those who want more detailed control over the whitespace around
1314 tokens, there are four parameters which can directly modify the
1315 default whitespace rules built into perltidy for any token. They
1316 are:
1317
1318 -wls=s or --want-left-space=s,
1319
1320 -nwls=s or --nowant-left-space=s,
1321
1322 -wrs=s or --want-right-space=s,
1323
1324 -nwrs=s or --nowant-right-space=s.
1325
1326 These parameters are each followed by a quoted string, s,
1327 containing a list of token types. No more than one of each of
1328 these parameters should be specified, because repeating a command-
1329 line parameter always overwrites the previous one before perltidy
1330 ever sees it.
1331
1332 To illustrate how these are used, suppose it is desired that there
1333 be no space on either side of the token types = + - / *. The
1334 following two parameters would specify this desire:
1335
1336 -nwls="= + - / *" -nwrs="= + - / *"
1337
1338 (Note that the token types are in quotes, and that they are
1339 separated by spaces). With these modified whitespace rules, the
1340 following line of math:
1341
1342 $root = -$b + sqrt( $b * $b - 4. * $a * $c ) / ( 2. * $a );
1343
1344 becomes this:
1345
1346 $root=-$b+sqrt( $b*$b-4.*$a*$c )/( 2.*$a );
1347
1348 These parameters should be considered to be hints to perltidy
1349 rather than fixed rules, because perltidy must try to resolve
1350 conflicts that arise between them and all of the other rules that
1351 it uses. One conflict that can arise is if, between two tokens,
1352 the left token wants a space and the right one doesn't. In this
1353 case, the token not wanting a space takes priority.
1354
1355 It is necessary to have a list of all token types in order to
1356 create this type of input. Such a list can be obtained by the
1357 command --dump-token-types. Also try the -D flag on a short
1358 snippet of code and look at the .DEBUG file to see the
1359 tokenization.
1360
1361 WARNING Be sure to put these tokens in quotes to avoid having them
1362 misinterpreted by your command shell.
1363
1364 Note1: Perltidy does always follow whitespace controls
1365 The various parameters controlling whitespace within a program are
1366 requests which perltidy follows as well as possible, but there are
1367 a number of situations where changing whitespace could change
1368 program behavior and is not done. Some of these are obvious; for
1369 example, we should not remove the space between the two plus
1370 symbols in '$x+ +$y' to avoid creating a '++' operator. Some are
1371 more subtle and involve the whitespace around bareword symbols and
1372 locations of possible filehandles. For example, consider the
1373 problem of formatting the following subroutine:
1374
1375 sub print_div {
1376 my ($x,$y)=@_;
1377 print $x/$y;
1378 }
1379
1380 Suppose the user requests that / signs have a space to the left but
1381 not to the right. Perltidy will refuse to do this, but if this were
1382 done the result would be
1383
1384 sub print_div {
1385 my ($x,$y)=@_;
1386 print $x /$y;
1387 }
1388
1389 If formatted in this way, the program will not run (at least with
1390 recent versions of perl) because the $x is taken to be a filehandle
1391 and / is assumed to start a quote. In a complex program, there
1392 might happen to be a / which terminates the multiline quote without
1393 a syntax error, allowing the program to run, but not as intended.
1394
1395 Related issues arise with other binary operator symbols, such as +
1396 and -, and in older versions of perl there could be problems with
1397 ternary operators. So to avoid changing program behavior, perltidy
1398 has the simple rule that whitespace around possible filehandles is
1399 left unchanged. Likewise, whitespace around barewords is left
1400 unchanged. The reason is that if the barewords are defined in
1401 other modules, or in code that has not even been written yet,
1402 perltidy will not have seen their prototypes and must treat them
1403 cautiously.
1404
1405 In perltidy this is implemented in the tokenizer by marking token
1406 following a print keyword as a special type Z. When formatting is
1407 being done, whitespace following this token type is generally left
1408 unchanged as a precaution against changing program behavior. This
1409 is excessively conservative but simple and easy to implement.
1410 Keywords which are treated similarly to print include printf, sort,
1411 exec, system. Changes in spacing around parameters following these
1412 keywords may have to be made manually. For example, the space, or
1413 lack of space, after the parameter $foo in the following line will
1414 be unchanged in formatting.
1415
1416 system($foo );
1417 system($foo);
1418
1419 To find if a token is of type Z you can use perltidy -DEBUG. For
1420 the first line above the result is
1421
1422 1: system($foo );
1423 1: kkkkkk{ZZZZb};
1424
1425 which shows that system is type k (keyword) and $foo is type Z.
1426
1427 Note2: Perltidy's whitespace rules are not perfect
1428 Despite these precautions, it is still possible to introduce syntax
1429 errors with some asymmetric whitespace rules, particularly when
1430 call parameters are not placed in containing parens or braces. For
1431 example, the following two lines will be parsed by perl without a
1432 syntax error:
1433
1434 # original programming, syntax ok
1435 my @newkeys = map $_-$nrecs+@data, @oldkeys;
1436
1437 # perltidy default, syntax ok
1438 my @newkeys = map $_ - $nrecs + @data, @oldkeys;
1439
1440 But the following will give a syntax error:
1441
1442 # perltidy -nwrs='-'
1443 my @newkeys = map $_ -$nrecs + @data, @oldkeys;
1444
1445 For another example, the following two lines will be parsed without
1446 syntax error:
1447
1448 # original programming, syntax ok
1449 for my $severity ( reverse $SEVERITY_LOWEST+1 .. $SEVERITY_HIGHEST ) { ... }
1450
1451 # perltidy default, syntax ok
1452 for my $severity ( reverse $SEVERITY_LOWEST + 1 .. $SEVERITY_HIGHEST ) { ... }
1453
1454 But the following will give a syntax error:
1455
1456 # perltidy -nwrs='+', syntax error:
1457 for my $severity ( reverse $SEVERITY_LOWEST +1 .. $SEVERITY_HIGHEST ) { ... }
1458
1459 To avoid subtle parsing problems like this, it is best to avoid
1460 spacing a binary operator asymmetrically with a space on the left
1461 but not on the right.
1462
1463 Space between specific keywords and opening paren
1464 When an opening paren follows a Perl keyword, no space is
1465 introduced after the keyword, unless it is (by default) one of
1466 these:
1467
1468 my local our and or xor eq ne if else elsif until unless
1469 while for foreach return switch case given when
1470
1471 These defaults can be modified with two commands:
1472
1473 -sak=s or --space-after-keyword=s adds keywords.
1474
1475 -nsak=s or --nospace-after-keyword=s removes keywords.
1476
1477 where s is a list of keywords (in quotes if necessary). For
1478 example,
1479
1480 my ( $a, $b, $c ) = @_; # default
1481 my( $a, $b, $c ) = @_; # -nsak="my local our"
1482
1483 The abbreviation -nsak='*' is equivalent to including all of the
1484 keywords in the above list.
1485
1486 When both -nsak=s and -sak=s commands are included, the -nsak=s
1487 command is executed first. For example, to have space after only
1488 the keywords (my, local, our) you could use -nsak="*" -sak="my
1489 local our".
1490
1491 To put a space after all keywords, see the next item.
1492
1493 Space between all keywords and opening parens
1494 When an opening paren follows a function or keyword, no space is
1495 introduced after the keyword except for the keywords noted in the
1496 previous item. To always put a space between a function or keyword
1497 and its opening paren, use the command:
1498
1499 -skp or --space-keyword-paren
1500
1501 You may also want to use the flag -sfp (next item) too.
1502
1503 Space between all function names and opening parens
1504 When an opening paren follows a function the default and
1505 recommended formatting is not to introduce a space. To cause a
1506 space to be introduced use:
1507
1508 -sfp or --space-function-paren
1509
1510 myfunc( $a, $b, $c ); # default
1511 myfunc ( $a, $b, $c ); # -sfp
1512
1513 You will probably also want to use the flag -skp (previous item)
1514 too.
1515
1516 The parameter is not recommended because spacing a function paren
1517 can make a program vulnerable to parsing problems by Perl. For
1518 example, the following two-line program will run as written but
1519 will have a syntax error if reformatted with -sfp:
1520
1521 if ( -e filename() ) { print "I'm here\n"; }
1522 sub filename { return $0 }
1523
1524 In this particular case the syntax error can be removed if the line
1525 order is reversed, so that Perl parses 'sub filename' first.
1526
1527 -fpva or --function-paren-vertical-alignment
1528 A side-effect of using the -sfp flag is that the parens may become
1529 vertically aligned. For example,
1530
1531 # perltidy -sfp
1532 myfun ( $aaa, $b, $cc );
1533 mylongfun ( $a, $b, $c );
1534
1535 This is the default behavior. To prevent this alignment use
1536 -nfpva:
1537
1538 # perltidy -sfp -nfpva
1539 myfun ( $aaa, $b, $cc );
1540 mylongfun ( $a, $b, $c );
1541
1542 -spp=n or --space-prototype-paren=n
1543 This flag can be used to control whether a function prototype is
1544 preceded by a space. For example, the following prototype does not
1545 have a space.
1546
1547 sub usage();
1548
1549 This integer n may have the value 0, 1, or 2 as follows:
1550
1551 -spp=0 means no space before the paren
1552 -spp=1 means follow the example of the source code [DEFAULT]
1553 -spp=2 means always put a space before the paren
1554
1555 The default is -spp=1, meaning that a space will be used if and
1556 only if there is one in the source code. Given the above line of
1557 code, the result of applying the different options would be:
1558
1559 sub usage(); # n=0 [no space]
1560 sub usage(); # n=1 [default; follows input]
1561 sub usage (); # n=2 [space]
1562
1563 -kpit=n or --keyword-paren-inner-tightness=n
1564 The space inside of an opening paren, which itself follows a
1565 certain keyword, can be controlled by this parameter. The space on
1566 the inside of the corresponding closing paren will be treated in
1567 the same (balanced) manner. This parameter has precedence over any
1568 other paren spacing rules. The values of n are as follows:
1569
1570 -kpit=0 means always put a space (not tight)
1571 -kpit=1 means ignore this parameter [default]
1572 -kpit=2 means never put a space (tight)
1573
1574 To illustrate, the following snippet is shown formatted in three
1575 ways:
1576
1577 if ( seek( DATA, 0, 0 ) ) { ... } # perltidy (default)
1578 if (seek(DATA, 0, 0)) { ... } # perltidy -pt=2
1579 if ( seek(DATA, 0, 0) ) { ... } # perltidy -pt=2 -kpit=0
1580
1581 In the second case the -pt=2 parameter makes all of the parens
1582 tight. In the third case the -kpit=0 flag causes the space within
1583 the 'if' parens to have a space, since 'if' is one of the keywords
1584 to which the -kpit flag applies by default. The remaining parens
1585 are still tight because of the -pt=2 parameter.
1586
1587 The set of keywords to which this parameter applies are by default
1588 are:
1589
1590 if elsif unless while until for foreach
1591
1592 These can be changed with the parameter -kpitl=s described in the
1593 next section.
1594
1595 -kpitl=string or --keyword-paren-inner-tightness=string
1596 This command can be used to change the keywords to which the the
1597 -kpit=n command applies. The parameter string is a required list
1598 either keywords or functions, which should be placed in quotes if
1599 there are more than one. By itself, this parameter does not cause
1600 any change in spacing, so the -kpit=n command is still required.
1601
1602 For example, the commands "-kpitl="if else while" -kpit=2" will
1603 cause the just the spaces inside parens following 'if', 'else',
1604 and 'while' keywords to follow the tightness value indicated by the
1605 -kpit=2 flag.
1606
1607 -lop or --logical-padding
1608 In the following example some extra space has been inserted on the
1609 second line between the two open parens. This extra space is called
1610 "logical padding" and is intended to help align similar things
1611 vertically in some logical or ternary expressions.
1612
1613 # perltidy [default formatting]
1614 $same =
1615 ( ( $aP eq $bP )
1616 && ( $aS eq $bS )
1617 && ( $aT eq $bT )
1618 && ( $a->{'title'} eq $b->{'title'} )
1619 && ( $a->{'href'} eq $b->{'href'} ) );
1620
1621 Note that this is considered to be a different operation from
1622 "vertical alignment" because space at just one line is being
1623 adjusted, whereas in "vertical alignment" the spaces at all lines
1624 are being adjusted. So it is sort of a local version of vertical
1625 alignment.
1626
1627 Here is an example involving a ternary operator:
1628
1629 # perltidy [default formatting]
1630 $bits =
1631 $top > 0xffff ? 32
1632 : $top > 0xff ? 16
1633 : $top > 1 ? 8
1634 : 1;
1635
1636 This behavior is controlled with the flag --logical-padding, which
1637 is set 'on' by default. If it is not desired it can be turned off
1638 using --nological-padding or -nlop. The above two examples become,
1639 with -nlop:
1640
1641 # perltidy -nlop
1642 $same =
1643 ( ( $aP eq $bP )
1644 && ( $aS eq $bS )
1645 && ( $aT eq $bT )
1646 && ( $a->{'title'} eq $b->{'title'} )
1647 && ( $a->{'href'} eq $b->{'href'} ) );
1648
1649 # perltidy -nlop
1650 $bits =
1651 $top > 0xffff ? 32
1652 : $top > 0xff ? 16
1653 : $top > 1 ? 8
1654 : 1;
1655
1656 Trimming whitespace around "qw" quotes
1657 -tqw or --trim-qw provide the default behavior of trimming spaces
1658 around multi-line "qw" quotes and indenting them appropriately.
1659
1660 -ntqw or --notrim-qw cause leading and trailing whitespace around
1661 multi-line "qw" quotes to be left unchanged. This option will not
1662 normally be necessary, but was added for testing purposes, because
1663 in some versions of perl, trimming "qw" quotes changes the syntax
1664 tree.
1665
1666 -sbq=n or --space-backslash-quote=n
1667 lines like
1668
1669 $str1=\"string1";
1670 $str2=\'string2';
1671
1672 can confuse syntax highlighters unless a space is included between
1673 the backslash and the single or double quotation mark.
1674
1675 this can be controlled with the value of n as follows:
1676
1677 -sbq=0 means no space between the backslash and quote
1678 -sbq=1 means follow the example of the source code
1679 -sbq=2 means always put a space between the backslash and quote
1680
1681 The default is -sbq=1, meaning that a space will be used if there
1682 is one in the source code.
1683
1684 Trimming trailing whitespace from lines of POD
1685 -trp or --trim-pod will remove trailing whitespace from lines of
1686 POD. The default is not to do this.
1687
1688 Comment Controls
1689 Perltidy has a number of ways to control the appearance of both block
1690 comments and side comments. The term block comment here refers to a
1691 full-line comment, whereas side comment will refer to a comment which
1692 appears on a line to the right of some code.
1693
1694 -ibc, --indent-block-comments
1695 Block comments normally look best when they are indented to the
1696 same level as the code which follows them. This is the default
1697 behavior, but you may use -nibc to keep block comments left-
1698 justified. Here is an example:
1699
1700 # this comment is indented (-ibc, default)
1701 if ($task) { yyy(); }
1702
1703 The alternative is -nibc:
1704
1705 # this comment is not indented (-nibc)
1706 if ($task) { yyy(); }
1707
1708 See also the next item, -isbc, as well as -sbc, for other ways to
1709 have some indented and some outdented block comments.
1710
1711 -isbc, --indent-spaced-block-comments
1712 If there is no leading space on the line, then the comment will not
1713 be indented, and otherwise it may be.
1714
1715 If both -ibc and -isbc are set, then -isbc takes priority.
1716
1717 -olc, --outdent-long-comments
1718 When -olc is set, lines which are full-line (block) comments longer
1719 than the value maximum-line-length will have their indentation
1720 removed. This is the default; use -nolc to prevent outdenting.
1721
1722 -msc=n, --minimum-space-to-comment=n
1723 Side comments look best when lined up several spaces to the right
1724 of code. Perltidy will try to keep comments at least n spaces to
1725 the right. The default is n=4 spaces.
1726
1727 -fpsc=n, --fixed-position-side-comment=n
1728 This parameter tells perltidy to line up side comments in column
1729 number n whenever possible. The default, n=0, will not do this.
1730
1731 -iscl, --ignore-side-comment-lengths
1732 This parameter causes perltidy to ignore the length of side
1733 comments when setting line breaks. The default, -niscl, is to
1734 include the length of side comments when breaking lines to stay
1735 within the length prescribed by the -l=n maximum line length
1736 parameter. For example, the following long single line would
1737 remain intact with -l=80 and -iscl:
1738
1739 perltidy -l=80 -iscl
1740 $vmsfile =~ s/;[\d\-]*$//; # Clip off version number; we can use a newer version as well
1741
1742 whereas without the -iscl flag the line will be broken:
1743
1744 perltidy -l=80
1745 $vmsfile =~ s/;[\d\-]*$//
1746 ; # Clip off version number; we can use a newer version as well
1747
1748 -ipc, --ignore-perlcritic-comments
1749 Perltidy, by default, will look for side comments beginning with ##
1750 no critic and ignore their lengths when making line break
1751 decisions, even if the user has not set -iscl. The reason is that
1752 an unwanted line break can make these special comments ineffective
1753 in controlling perlcritic.
1754
1755 Setting --ignore-perlcritic-comments tells perltidy not to look for
1756 these ## no critic comments.
1757
1758 -hsc, --hanging-side-comments
1759 By default, perltidy tries to identify and align "hanging side
1760 comments", which are something like this:
1761
1762 my $IGNORE = 0; # This is a side comment
1763 # This is a hanging side comment
1764 # And so is this
1765
1766 A comment is considered to be a hanging side comment if (1) it
1767 immediately follows a line with a side comment, or another hanging
1768 side comment, and (2) there is some leading whitespace on the line.
1769 To deactivate this feature, use -nhsc or --nohanging-side-comments.
1770 If block comments are preceded by a blank line, or have no leading
1771 whitespace, they will not be mistaken as hanging side comments.
1772
1773 Closing Side Comments
1774 A closing side comment is a special comment which perltidy can
1775 automatically create and place after the closing brace of a code
1776 block. They can be useful for code maintenance and debugging. The
1777 command -csc (or --closing-side-comments) adds or updates closing
1778 side comments. For example, here is a small code snippet
1779
1780 sub message {
1781 if ( !defined( $_[0] ) ) {
1782 print("Hello, World\n");
1783 }
1784 else {
1785 print( $_[0], "\n" );
1786 }
1787 }
1788
1789 And here is the result of processing with "perltidy -csc":
1790
1791 sub message {
1792 if ( !defined( $_[0] ) ) {
1793 print("Hello, World\n");
1794 }
1795 else {
1796 print( $_[0], "\n" );
1797 }
1798 } ## end sub message
1799
1800 A closing side comment was added for "sub message" in this case,
1801 but not for the "if" and "else" blocks, because they were below the
1802 6 line cutoff limit for adding closing side comments. This limit
1803 may be changed with the -csci command, described below.
1804
1805 The command -dcsc (or --delete-closing-side-comments) reverses this
1806 process and removes these comments.
1807
1808 Several commands are available to modify the behavior of these two
1809 basic commands, -csc and -dcsc:
1810
1811 -csci=n, or --closing-side-comment-interval=n
1812 where "n" is the minimum number of lines that a block must have
1813 in order for a closing side comment to be added. The default
1814 value is "n=6". To illustrate:
1815
1816 # perltidy -csci=2 -csc
1817 sub message {
1818 if ( !defined( $_[0] ) ) {
1819 print("Hello, World\n");
1820 } ## end if ( !defined( $_[0] ))
1821 else {
1822 print( $_[0], "\n" );
1823 } ## end else [ if ( !defined( $_[0] ))
1824 } ## end sub message
1825
1826 Now the "if" and "else" blocks are commented. However, now
1827 this has become very cluttered.
1828
1829 -cscp=string, or --closing-side-comment-prefix=string
1830 where string is the prefix used before the name of the block
1831 type. The default prefix, shown above, is "## end". This
1832 string will be added to closing side comments, and it will also
1833 be used to recognize them in order to update, delete, and
1834 format them. Any comment identified as a closing side comment
1835 will be placed just a single space to the right of its closing
1836 brace.
1837
1838 -cscl=string, or --closing-side-comment-list
1839 where "string" is a list of block types to be tagged with
1840 closing side comments. By default, all code block types
1841 preceded by a keyword or label (such as "if", "sub", and so on)
1842 will be tagged. The -cscl command changes the default list to
1843 be any selected block types; see "Specifying Block Types". For
1844 example, the following command requests that only "sub"'s,
1845 labels, "BEGIN", and "END" blocks be affected by any -csc or
1846 -dcsc operation:
1847
1848 -cscl="sub : BEGIN END"
1849
1850 -csct=n, or --closing-side-comment-maximum-text=n
1851 The text appended to certain block types, such as an "if"
1852 block, is whatever lies between the keyword introducing the
1853 block, such as "if", and the opening brace. Since this might
1854 be too much text for a side comment, there needs to be a limit,
1855 and that is the purpose of this parameter. The default value
1856 is "n=20", meaning that no additional tokens will be appended
1857 to this text after its length reaches 20 characters. Omitted
1858 text is indicated with "...". (Tokens, including sub names,
1859 are never truncated, however, so actual lengths may exceed
1860 this). To illustrate, in the above example, the appended text
1861 of the first block is " ( !defined( $_[0] )...". The existing
1862 limit of "n=20" caused this text to be truncated, as indicated
1863 by the "...". See the next flag for additional control of the
1864 abbreviated text.
1865
1866 -cscb, or --closing-side-comments-balanced
1867 As discussed in the previous item, when the closing-side-
1868 comment-maximum-text limit is exceeded the comment text must be
1869 truncated. Older versions of perltidy terminated with three
1870 dots, and this can still be achieved with -ncscb:
1871
1872 perltidy -csc -ncscb
1873 } ## end foreach my $foo (sort { $b cmp $a ...
1874
1875 However this causes a problem with editors which cannot
1876 recognize comments or are not configured to do so because they
1877 cannot "bounce" around in the text correctly. The -cscb flag
1878 has been added to help them by appending appropriate balancing
1879 structure:
1880
1881 perltidy -csc -cscb
1882 } ## end foreach my $foo (sort { $b cmp $a ... })
1883
1884 The default is -cscb.
1885
1886 -csce=n, or --closing-side-comment-else-flag=n
1887 The default, n=0, places the text of the opening "if" statement
1888 after any terminal "else".
1889
1890 If n=2 is used, then each "elsif" is also given the text of the
1891 opening "if" statement. Also, an "else" will include the text
1892 of a preceding "elsif" statement. Note that this may result
1893 some long closing side comments.
1894
1895 If n=1 is used, the results will be the same as n=2 whenever
1896 the resulting line length is less than the maximum allowed.
1897
1898 -cscb, or --closing-side-comments-balanced
1899 When using closing-side-comments, and the closing-side-comment-
1900 maximum-text limit is exceeded, then the comment text must be
1901 abbreviated. It is terminated with three dots if the -cscb
1902 flag is negated:
1903
1904 perltidy -csc -ncscb
1905 } ## end foreach my $foo (sort { $b cmp $a ...
1906
1907 This causes a problem with older editors which do not recognize
1908 comments because they cannot "bounce" around in the text
1909 correctly. The -cscb flag tries to help them by appending
1910 appropriate terminal balancing structures:
1911
1912 perltidy -csc -cscb
1913 } ## end foreach my $foo (sort { $b cmp $a ... })
1914
1915 The default is -cscb.
1916
1917 -cscw, or --closing-side-comment-warnings
1918 This parameter is intended to help make the initial transition
1919 to the use of closing side comments. It causes two things to
1920 happen if a closing side comment replaces an existing,
1921 different closing side comment: first, an error message will
1922 be issued, and second, the original side comment will be placed
1923 alone on a new specially marked comment line for later
1924 attention.
1925
1926 The intent is to avoid clobbering existing hand-written side
1927 comments which happen to match the pattern of closing side
1928 comments. This flag should only be needed on the first run with
1929 -csc.
1930
1931 Important Notes on Closing Side Comments:
1932
1933 • Closing side comments are only placed on lines terminated with
1934 a closing brace. Certain closing styles, such as the use of
1935 cuddled elses (-ce), preclude the generation of some closing
1936 side comments.
1937
1938 • Please note that adding or deleting of closing side comments
1939 takes place only through the commands -csc or -dcsc. The other
1940 commands, if used, merely modify the behavior of these two
1941 commands.
1942
1943 • It is recommended that the -cscw flag be used along with -csc
1944 on the first use of perltidy on a given file. This will
1945 prevent loss of any existing side comment data which happens to
1946 have the csc prefix.
1947
1948 • Once you use -csc, you should continue to use it so that any
1949 closing side comments remain correct as code changes.
1950 Otherwise, these comments will become incorrect as the code is
1951 updated.
1952
1953 • If you edit the closing side comments generated by perltidy,
1954 you must also change the prefix to be different from the
1955 closing side comment prefix. Otherwise, your edits will be
1956 lost when you rerun perltidy with -csc. For example, you
1957 could simply change "## end" to be "## End", since the test is
1958 case sensitive. You may also want to use the -ssc flag to keep
1959 these modified closing side comments spaced the same as actual
1960 closing side comments.
1961
1962 • Temporarily generating closing side comments is a useful
1963 technique for exploring and/or debugging a perl script,
1964 especially one written by someone else. You can always remove
1965 them with -dcsc.
1966
1967 Static Block Comments
1968 Static block comments are block comments with a special leading
1969 pattern, "##" by default, which will be treated slightly
1970 differently from other block comments. They effectively behave as
1971 if they had glue along their left and top edges, because they stick
1972 to the left edge and previous line when there is no blank spaces in
1973 those places. This option is particularly useful for controlling
1974 how commented code is displayed.
1975
1976 -sbc, --static-block-comments
1977 When -sbc is used, a block comment with a special leading
1978 pattern, "##" by default, will be treated specially.
1979
1980 Comments so identified are treated as follows:
1981
1982 • If there is no leading space on the line, then the comment
1983 will not be indented, and otherwise it may be,
1984
1985 • no new blank line will be inserted before such a comment,
1986 and
1987
1988 • such a comment will never become a hanging side comment.
1989
1990 For example, assuming @month_of_year is left-adjusted:
1991
1992 @month_of_year = ( # -sbc (default)
1993 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
1994 ## 'Dec', 'Nov'
1995 'Nov', 'Dec');
1996
1997 Without this convention, the above code would become
1998
1999 @month_of_year = ( # -nsbc
2000 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
2001
2002 ## 'Dec', 'Nov'
2003 'Nov', 'Dec'
2004 );
2005
2006 which is not as clear. The default is to use -sbc. This may
2007 be deactivated with -nsbc.
2008
2009 -sbcp=string, --static-block-comment-prefix=string
2010 This parameter defines the prefix used to identify static block
2011 comments when the -sbc parameter is set. The default prefix is
2012 "##", corresponding to "-sbcp=##". The prefix is actually part
2013 of a perl pattern used to match lines and it must either begin
2014 with "#" or "^#". In the first case a prefix ^\s* will be
2015 added to match any leading whitespace, while in the second case
2016 the pattern will match only comments with no leading
2017 whitespace. For example, to identify all comments as static
2018 block comments, one would use "-sbcp=#". To identify all left-
2019 adjusted comments as static block comments, use "-sbcp='^#'".
2020
2021 Please note that -sbcp merely defines the pattern used to
2022 identify static block comments; it will not be used unless the
2023 switch -sbc is set. Also, please be aware that since this
2024 string is used in a perl regular expression which identifies
2025 these comments, it must enable a valid regular expression to be
2026 formed.
2027
2028 A pattern which can be useful is:
2029
2030 -sbcp=^#{2,}[^\s#]
2031
2032 This pattern requires a static block comment to have at least
2033 one character which is neither a # nor a space. It allows a
2034 line containing only '#' characters to be rejected as a static
2035 block comment. Such lines are often used at the start and end
2036 of header information in subroutines and should not be
2037 separated from the intervening comments, which typically begin
2038 with just a single '#'.
2039
2040 -osbc, --outdent-static-block-comments
2041 The command -osbc will cause static block comments to be
2042 outdented by 2 spaces (or whatever -ci=n has been set to), if
2043 possible.
2044
2045 Static Side Comments
2046 Static side comments are side comments with a special leading
2047 pattern. This option can be useful for controlling how commented
2048 code is displayed when it is a side comment.
2049
2050 -ssc, --static-side-comments
2051 When -ssc is used, a side comment with a static leading
2052 pattern, which is "##" by default, will be spaced only a single
2053 space from previous character, and it will not be vertically
2054 aligned with other side comments.
2055
2056 The default is -nssc.
2057
2058 -sscp=string, --static-side-comment-prefix=string
2059 This parameter defines the prefix used to identify static side
2060 comments when the -ssc parameter is set. The default prefix is
2061 "##", corresponding to "-sscp=##".
2062
2063 Please note that -sscp merely defines the pattern used to
2064 identify static side comments; it will not be used unless the
2065 switch -ssc is set. Also, note that this string is used in a
2066 perl regular expression which identifies these comments, so it
2067 must enable a valid regular expression to be formed.
2068
2069 Skipping Selected Sections of Code
2070 Selected lines of code may be passed verbatim to the output without any
2071 formatting by marking the starting and ending lines with special
2072 comments. There are two options for doing this. The first option is
2073 called --format-skipping or -fs, and the second option is called
2074 --code-skipping or -cs.
2075
2076 In both cases the lines of code will be output without any changes.
2077 The difference is that in --format-skipping perltidy will still parse
2078 the marked lines of code and check for errors, whereas in
2079 --code-skipping perltidy will simply pass the lines to the output
2080 without any checking.
2081
2082 Both of these features are enabled by default and are invoked with
2083 special comment markers. --format-skipping uses starting and ending
2084 markers '#<<<' and '#>>>', like this:
2085
2086 #<<< format skipping: do not let perltidy change my nice formatting
2087 my @list = (1,
2088 1, 1,
2089 1, 2, 1,
2090 1, 3, 3, 1,
2091 1, 4, 6, 4, 1,);
2092 #>>>
2093
2094 --code-skipping uses starting and ending markers '#<<V' and '#>>V',
2095 like this:
2096
2097 #<<V code skipping: perltidy will pass this verbatim without error checking
2098
2099 token ident_digit {
2100 [ [ <?word> | _ | <?digit> ] <?ident_digit>
2101 | <''>
2102 ]
2103 };
2104
2105 #>>V
2106
2107 Additional text may appear on the special comment lines provided that
2108 it is separated from the marker by at least one space, as in the above
2109 examples.
2110
2111 Any number of code-skipping or format-skipping sections may appear in a
2112 file. If an opening code-skipping or format-skipping comment is not
2113 followed by a corresponding closing comment, then skipping continues to
2114 the end of the file. If a closing code-skipping or format-skipping
2115 comment appears in a file but does not follow a corresponding opening
2116 comment, then it is treated as an ordinary comment without any special
2117 meaning.
2118
2119 It is recommended to use --code-skipping only if you need to hide a
2120 block of an extended syntax which would produce errors if parsed by
2121 perltidy, and use --format-skipping otherwise. This is because the
2122 --format-skipping option provides the benefits of error checking, and
2123 there are essentially no limitations on which lines to which it can be
2124 applied. The --code-skipping option, on the other hand, does not do
2125 error checking and its use is more restrictive because the code which
2126 remains, after skipping the marked lines, must be syntactically correct
2127 code with balanced containers.
2128
2129 These features should be used sparingly to avoid littering code with
2130 markers, but they can be helpful for working around occasional
2131 problems.
2132
2133 Note that it may be possible to avoid the use of --format-skipping for
2134 the specific case of a comma-separated list of values, as in the above
2135 example, by simply inserting a blank or comment somewhere between the
2136 opening and closing parens. See the section "Controlling List
2137 Formatting".
2138
2139 The following sections describe the available controls for these
2140 options. They should not normally be needed.
2141
2142 -fs, --format-skipping
2143 As explained above, this flag, which is enabled by default, causes
2144 any code between special beginning and ending comment markers to be
2145 passed to the output without formatting. The code between the
2146 comments is still checked for errors however. The default
2147 beginning marker is #<<< and the default ending marker is #>>>.
2148
2149 Format skipping begins when a format skipping beginning comment is
2150 seen and continues until a format-skipping ending comment is found.
2151
2152 This feature can be disabled with -nfs. This should not normally
2153 be necessary.
2154
2155 -fsb=string, --format-skipping-begin=string
2156 This and the next parameter allow the special beginning and ending
2157 comments to be changed. However, it is recommended that they only
2158 be changed if there is a conflict between the default values and
2159 some other use. If they are used, it is recommended that they only
2160 be entered in a .perltidyrc file, rather than on a command line.
2161 This is because properly escaping these parameters on a command
2162 line can be difficult.
2163
2164 If changed comment markers do not appear to be working, use the
2165 -log flag and examine the .LOG file to see if and where they are
2166 being detected.
2167
2168 The -fsb=string parameter may be used to change the beginning
2169 marker for format skipping. The default is equivalent to
2170 -fsb='#<<<'. The string that you enter must begin with a # and
2171 should be in quotes as necessary to get past the command shell of
2172 your system. It is actually the leading text of a pattern that is
2173 constructed by appending a '\s', so you must also include
2174 backslashes for characters to be taken literally rather than as
2175 patterns.
2176
2177 Some examples show how example strings become patterns:
2178
2179 -fsb='#\{\{\{' becomes /^#\{\{\{\s/ which matches #{{{ but not #{{{{
2180 -fsb='#\*\*' becomes /^#\*\*\s/ which matches #** but not #***
2181 -fsb='#\*{2,}' becomes /^#\*{2,}\s/ which matches #** and #*****
2182
2183 -fse=string, --format-skipping-end=string
2184 The -fse=string is the corresponding parameter used to change the
2185 ending marker for format skipping. The default is equivalent to
2186 -fse='#<<<'.
2187
2188 The beginning and ending strings may be the same, but it is
2189 preferable to make them different for clarity.
2190
2191 -cs, --code-skipping
2192 As explained above, this flag, which is enabled by default, causes
2193 any code between special beginning and ending comment markers to be
2194 directly passed to the output without any error checking or
2195 formatting. Essentially, perltidy treats it as if it were a block
2196 of arbitrary text. The default beginning marker is #<<V and the
2197 default ending marker is #>>V.
2198
2199 This feature can be disabled with -ncs. This should not normally
2200 be necessary.
2201
2202 -csb=string, --code-skipping-begin=string
2203 This may be used to change the beginning comment for a
2204 --code-skipping section, and its use is similar to the -fsb=string.
2205 The default is equivalent to -csb='#<<V'.
2206
2207 -cse=string, --code-skipping-end=string
2208 This may be used to change the ending comment for a --code-skipping
2209 section, and its use is similar to the -fse=string. The default is
2210 equivalent to -cse='#>>V'.
2211
2212 Formatting a Limited Range of Lines
2213 A command --line-range-tidy=n1:n2 is available to process just a
2214 selected range of lines of an input stream with perltidy. This command
2215 is mainly of interest for programming interactive code editors. When
2216 it is used, the entire input stream is read but just the selected range
2217 of lines of the input file are processed by the perltidy tokenizer and
2218 formatter, and then the stream is reassembled for output. The selected
2219 lines need to contain a complete statement or balanced container.
2220 Otherwise, a syntax error will occur and the code will not be tidied.
2221 There are a couple of limitations on the use of this command: (1) it
2222 may not be applied to multiple files, and (2) it only applies to code
2223 tidying and not, for example, html formatting.
2224
2225 -lrt=n1:n2, --line-range-tidy=n1:n2
2226 The range of lines is specified by integers n1 and n2, where n1 is
2227 the first line number to be formatted (start counting with 1) and
2228 n2 is the last line number to be formatted. If n2 is not given, or
2229 exceeds the actual number of lines, then formatting continues to
2230 the end of the file.
2231
2232 Examples:
2233
2234 -line-range-tidy=43:109 # tidy lines 43 through 109
2235 -line-range-tidy=' 43 : 109' # tidy lines 43 through 109 (spaces ok in quotes)
2236 -line-range-tidy=1: # tidy all lines
2237 -line-range-tidy=0:90 # ERROR (n1 must be >= 1)
2238
2239 Line Break Control
2240 The parameters in this and the next sections control breaks after non-
2241 blank lines of code. Blank lines are controlled separately by
2242 parameters in the section "Blank Line Control".
2243
2244 -dnl, --delete-old-newlines
2245 By default, perltidy first deletes all old line break locations,
2246 and then it looks for good break points to match the desired line
2247 length. Use -ndnl or --nodelete-old-newlines to force perltidy to
2248 retain all old line break points.
2249
2250 -anl, --add-newlines
2251 By default, perltidy will add line breaks when necessary to create
2252 continuations of long lines and to improve the script appearance.
2253 Use -nanl or --noadd-newlines to prevent any new line breaks.
2254
2255 This flag does not prevent perltidy from eliminating existing line
2256 breaks; see --freeze-newlines to completely prevent changes to line
2257 break points.
2258
2259 -fnl, --freeze-newlines
2260 If you do not want any changes to the line breaks within lines of
2261 code in your script, set -fnl, and they will remain fixed, and the
2262 rest of the commands in this section and sections "Controlling List
2263 Formatting", "Retaining or Ignoring Existing Line Breaks". You may
2264 want to use -noll with this.
2265
2266 Note: If you also want to keep your blank lines exactly as they
2267 are, you can use the -fbl flag which is described in the section
2268 "Blank Line Control".
2269
2270 Controlling Breaks at Braces, Parens, and Square Brackets
2271 -ce, --cuddled-else
2272 Enable the "cuddled else" style, in which "else" and "elsif" are
2273 follow immediately after the curly brace closing the previous
2274 block. The default is not to use cuddled elses, and is indicated
2275 with the flag -nce or --nocuddled-else. Here is a comparison of
2276 the alternatives:
2277
2278 # -ce
2279 if ($task) {
2280 yyy();
2281 } else {
2282 zzz();
2283 }
2284
2285 # -nce (default)
2286 if ($task) {
2287 yyy();
2288 }
2289 else {
2290 zzz();
2291 }
2292
2293 In this example the keyword else is placed on the same line which
2294 begins with the preceding closing block brace and is followed by
2295 its own opening block brace on the same line. Other keywords and
2296 function names which are formatted with this "cuddled" style are
2297 elsif, continue, catch, finally.
2298
2299 Other block types can be formatted by specifying their names on a
2300 separate parameter -cbl, described in a later section.
2301
2302 Cuddling between a pair of code blocks requires that the closing
2303 brace of the first block start a new line. If this block is
2304 entirely on one line in the input file, it is necessary to decide
2305 if it should be broken to allow cuddling. This decision is
2306 controlled by the flag -cbo=n discussed below. The default and
2307 recommended value of -cbo=1 bases this decision on the first block
2308 in the chain. If it spans multiple lines then cuddling is made and
2309 continues along the chain, regardless of the sizes of subsequent
2310 blocks. Otherwise, short lines remain intact.
2311
2312 So for example, the -ce flag would not have any effect if the above
2313 snippet is rewritten as
2314
2315 if ($task) { yyy() }
2316 else { zzz() }
2317
2318 If the first block spans multiple lines, then cuddling can be done
2319 and will continue for the subsequent blocks in the chain, as
2320 illustrated in the previous snippet.
2321
2322 If there are blank lines between cuddled blocks they will be
2323 eliminated. If there are comments after the closing brace where
2324 cuddling would occur then cuddling will be prevented. If this
2325 occurs, cuddling will restart later in the chain if possible.
2326
2327 -cb, --cuddled-blocks
2328 This flag is equivalent to -ce.
2329
2330 -cbl, --cuddled-block-list
2331 The built-in default cuddled block types are else, elsif, continue,
2332 catch, finally.
2333
2334 Additional block types to which the -cuddled-blocks style applies
2335 can be defined by this parameter. This parameter is a character
2336 string, giving a list of block types separated by commas or spaces.
2337 For example, to cuddle code blocks of type sort, map and grep, in
2338 addition to the default types, the string could be set to
2339
2340 -cbl="sort map grep"
2341
2342 or equivalently
2343
2344 -cbl=sort,map,grep
2345
2346 Note however that these particular block types are typically short
2347 so there might not be much opportunity for the cuddled format
2348 style.
2349
2350 Using commas avoids the need to protect spaces with quotes.
2351
2352 As a diagnostic check, the flag --dump-cuddled-block-list or -dcbl
2353 can be used to view the hash of values that are generated by this
2354 flag.
2355
2356 Finally, note that the -cbl flag by itself merely specifies which
2357 blocks are formatted with the cuddled format. It has no effect
2358 unless this formatting style is activated with -ce.
2359
2360 -cblx, --cuddled-block-list-exclusive
2361 When cuddled else formatting is selected with -ce, setting this
2362 flag causes perltidy to ignore its built-in defaults and rely
2363 exclusively on the block types specified on the -cbl flag described
2364 in the previous section. For example, to avoid using cuddled catch
2365 and finally, which are among the defaults, the following set of
2366 parameters could be used:
2367
2368 perltidy -ce -cbl='else elsif continue' -cblx
2369
2370 -cbo=n, --cuddled-break-option=n
2371 Cuddled formatting is only possible between a pair of code blocks
2372 if the closing brace of the first block starts a new line. If a
2373 block is encountered which is entirely on a single line, and
2374 cuddled formatting is selected, it is necessary to make a decision
2375 as to whether or not to "break" the block, meaning to cause it to
2376 span multiple lines. This parameter controls that decision. The
2377 options are:
2378
2379 cbo=0 Never force a short block to break.
2380 cbo=1 If the first of a pair of blocks is broken in the input file,
2381 then break the second [DEFAULT].
2382 cbo=2 Break open all blocks for maximal cuddled formatting.
2383
2384 The default and recommended value is cbo=1. With this value, if
2385 the starting block of a chain spans multiple lines, then a cascade
2386 of breaks will occur for remaining blocks causing the entire chain
2387 to be cuddled.
2388
2389 The option cbo=0 can produce erratic cuddling if there are numerous
2390 one-line blocks.
2391
2392 The option cbo=2 produces maximal cuddling but will not allow any
2393 short blocks.
2394
2395 -bl, --opening-brace-on-new-line, or --brace-left
2396 Use the flag -bl to place an opening block brace on a new line:
2397
2398 if ( $input_file eq '-' )
2399 {
2400 ...
2401 }
2402
2403 By default it applies to all structural blocks except sort map grep
2404 eval and anonymous subs.
2405
2406 The default is -nbl which places an opening brace on the same line
2407 as the keyword introducing it if possible. For example,
2408
2409 # default
2410 if ( $input_file eq '-' ) {
2411 ...
2412 }
2413
2414 When -bl is set, the blocks to which this applies can be controlled
2415 with the parameters --brace-left-list and
2416 -brace-left-exclusion-list described in the next sections.
2417
2418 -bll=s, --brace-left-list=s
2419 Use this parameter to change the types of block braces for which
2420 the -bl flag applies; see "Specifying Block Types". For example,
2421 -bll='if elsif else sub' would apply it to only "if/elsif/else" and
2422 named sub blocks. The default is all blocks, -bll='*'.
2423
2424 -blxl=s, --brace-left-exclusion-list=s
2425 Use this parameter to exclude types of block braces for which the
2426 -bl flag applies; see "Specifying Block Types". For example, the
2427 default settings -bll='*' and -blxl='sort map grep eval asub' mean
2428 all blocks except sort map grep eval and anonymous sub blocks.
2429
2430 Note that the lists -bll=s and -blxl=s control the behavior of the
2431 -bl flag but have no effect unless the -bl flag is set.
2432
2433 -sbl, --opening-sub-brace-on-new-line
2434 The flag -sbl provides a shortcut way to turn on -bl just for named
2435 subs. The same effect can be achieved by turning on -bl with the
2436 block list set as -bll='sub'.
2437
2438 For example,
2439
2440 perltidy -sbl
2441
2442 produces this result:
2443
2444 sub message
2445 {
2446 if (!defined($_[0])) {
2447 print("Hello, World\n");
2448 }
2449 else {
2450 print($_[0], "\n");
2451 }
2452 }
2453
2454 This flag is negated with -nsbl, which is the default.
2455
2456 -asbl, --opening-anonymous-sub-brace-on-new-line
2457 The flag -asbl is like the -sbl flag except that it applies to
2458 anonymous sub's instead of named subs. For example
2459
2460 perltidy -asbl
2461
2462 produces this result:
2463
2464 $a = sub
2465 {
2466 if ( !defined( $_[0] ) ) {
2467 print("Hello, World\n");
2468 }
2469 else {
2470 print( $_[0], "\n" );
2471 }
2472 };
2473
2474 This flag is negated with -nasbl, and the default is -nasbl.
2475
2476 -bli, --brace-left-and-indent
2477 The flag -bli is similar to the -bl flag but in addition it causes
2478 one unit of continuation indentation ( see -ci ) to be placed
2479 before an opening and closing block braces.
2480
2481 For example, perltidy -bli gives
2482
2483 if ( $input_file eq '-' )
2484 {
2485 important_function();
2486 }
2487
2488 By default, this extra indentation occurs for block types: if,
2489 elsif, else, unless, while, for, foreach, do, and also named subs
2490 and blocks preceded by a label. The next item shows how to change
2491 this.
2492
2493 Note: The -bli flag is similar to the -bl flag, with the difference
2494 being that braces get indented. But these two flags are
2495 implemented independently, and have different default settings for
2496 historical reasons. If desired, a mixture of effects can be
2497 achieved if desired by turning them both on with different -list
2498 settings. In the event that both settings are selected for a
2499 certain block type, the -bli style has priority.
2500
2501 -blil=s, --brace-left-and-indent-list=s
2502 Use this parameter to change the types of block braces for which
2503 the -bli flag applies; see "Specifying Block Types".
2504
2505 The default is -blil='if else elsif unless while for foreach do :
2506 sub'.
2507
2508 -blixl=s, --brace-left-and-indent-exclusion-list=s
2509 Use this parameter to exclude types of block braces for which the
2510 -bli flag applies; see "Specifying Block Types".
2511
2512 This might be useful in conjunction with selecting all blocks
2513 -blil='*'. The default setting is -blixl=' ', which does not
2514 exclude any blocks.
2515
2516 Note that the two parameters -blil and -blixl control the behavior
2517 of the -bli flag but have no effect unless the -bli flag is set.
2518
2519 -bar, --opening-brace-always-on-right
2520 The default style, -nbl places the opening code block brace on a
2521 new line if it does not fit on the same line as the opening
2522 keyword, like this:
2523
2524 if ( $bigwasteofspace1 && $bigwasteofspace2
2525 || $bigwasteofspace3 && $bigwasteofspace4 )
2526 {
2527 big_waste_of_time();
2528 }
2529
2530 To force the opening brace to always be on the right, use the -bar
2531 flag. In this case, the above example becomes
2532
2533 if ( $bigwasteofspace1 && $bigwasteofspace2
2534 || $bigwasteofspace3 && $bigwasteofspace4 ) {
2535 big_waste_of_time();
2536 }
2537
2538 A conflict occurs if both -bl and -bar are specified.
2539
2540 -cpb, --cuddled-paren-brace
2541 A related parameter, --cuddled-paren-brace, causes perltidy to join
2542 two lines which otherwise would be
2543
2544 )
2545 {
2546
2547 to be
2548
2549 ) {
2550
2551 For example:
2552
2553 # default
2554 foreach my $dir (
2555 '05_lexer', '07_token', '08_regression', '11_util',
2556 '13_data', '15_transform'
2557 )
2558 {
2559 ...
2560 }
2561
2562 # perltidy -cpb
2563 foreach my $dir (
2564 '05_lexer', '07_token', '08_regression', '11_util',
2565 '13_data', '15_transform'
2566 ) {
2567 ...;
2568 }
2569
2570 -otr, --opening-token-right and related flags
2571 The -otr flag is a hint that perltidy should not place a break
2572 between a comma and an opening token. For example:
2573
2574 # default formatting
2575 push @{ $self->{$module}{$key} },
2576 {
2577 accno => $ref->{accno},
2578 description => $ref->{description}
2579 };
2580
2581 # perltidy -otr
2582 push @{ $self->{$module}{$key} }, {
2583 accno => $ref->{accno},
2584 description => $ref->{description}
2585 };
2586
2587 The flag -otr is actually an abbreviation for three other flags
2588 which can be used to control parens, hash braces, and square
2589 brackets separately if desired:
2590
2591 -opr or --opening-paren-right
2592 -ohbr or --opening-hash-brace-right
2593 -osbr or --opening-square-bracket-right
2594
2595 -bbhb=n, --break-before-hash-brace=n and related flags
2596 When a list of items spans multiple lines, the default formatting
2597 is to place the opening brace (or other container token) at the end
2598 of the starting line, like this:
2599
2600 $romanNumerals = {
2601 one => 'I',
2602 two => 'II',
2603 three => 'III',
2604 four => 'IV',
2605 };
2606
2607 This flag can change the default behavior to cause a line break to
2608 be placed before the opening brace according to the value given to
2609 the integer n:
2610
2611 -bbhb=0 never break [default]
2612 -bbhb=1 stable: break if the input script had a break
2613 -bbhb=2 break if list is 'complex' (see note below)
2614 -bbhb=3 always break
2615
2616 For example,
2617
2618 # perltidy -bbhb=3
2619 $romanNumerals =
2620 {
2621 one => 'I',
2622 two => 'II',
2623 three => 'III',
2624 four => 'IV',
2625 };
2626
2627 There are several points to note about this flag:
2628
2629 • This parameter only applies if the opening brace is preceded by
2630 an '=' or '=>'.
2631
2632 • This parameter only applies if the contents of the container
2633 looks like a list. The contents need to contain some commas or
2634 '=>'s at the next interior level to be considered a list.
2635
2636 • For the n=2 option, a list is considered 'complex' if it is
2637 part of a nested list structure which spans multiple lines in
2638 the input file.
2639
2640 • If multiple opening tokens have been 'welded' together with the
2641 -wn parameter, then this parameter has no effect.
2642
2643 • The indentation of the braces will normally be one level of
2644 continuation indentation by default. This can be changed with
2645 the parameter -bbhbi=n in the next section.
2646
2647 • Similar flags for controlling parens and square brackets are
2648 given in the subsequent section.
2649
2650 -bbhbi=n, --break-before-hash-brace-and-indent=n
2651 This flag is a companion to -bbhb=n for controlling the indentation
2652 of an opening hash brace which is placed on a new line by that
2653 parameter. The indentation is as follows:
2654
2655 -bbhbi=0 one continuation level [default]
2656 -bbhbi=1 outdent by one continuation level
2657 -bbhbi=2 indent one full indentation level
2658
2659 For example:
2660
2661 # perltidy -bbhb=3 -bbhbi=1
2662 $romanNumerals =
2663 {
2664 one => 'I',
2665 two => 'II',
2666 three => 'III',
2667 four => 'IV',
2668 };
2669
2670 # perltidy -bbhb=3 -bbhbi=2
2671 $romanNumerals =
2672 {
2673 one => 'I',
2674 two => 'II',
2675 three => 'III',
2676 four => 'IV',
2677 };
2678
2679 Note that this parameter has no effect unless -bbhb=n is also set.
2680
2681 -bbsb=n, --break-before-square-bracket=n
2682 This flag is similar to the flag described above, except it applies
2683 to lists contained within square brackets.
2684
2685 -bbsb=0 never break [default]
2686 -bbsb=1 stable: break if the input script had a break
2687 -bbsb=2 break if list is 'complex' (part of nested list structure)
2688 -bbsb=3 always break
2689
2690 -bbsbi=n, --break-before-square-bracket-and-indent=n
2691 This flag is a companion to -bbsb=n for controlling the indentation
2692 of an opening square bracket which is placed on a new line by that
2693 parameter. The indentation is as follows:
2694
2695 -bbsbi=0 one continuation level [default]
2696 -bbsbi=1 outdent by one continuation level
2697 -bbsbi=2 indent one full indentation level
2698
2699 -bbp=n, --break-before-paren=n
2700 This flag is similar to -bbhb=n, described above, except it applies
2701 to lists contained within parens.
2702
2703 -bbp=0 never break [default]
2704 -bbp=1 stable: break if the input script had a break
2705 -bpb=2 break if list is 'complex' (part of nested list structure)
2706 -bbp=3 always break
2707
2708 -bbpi=n, --break-before-paren-and-indent=n
2709 This flag is a companion to -bbp=n for controlling the indentation
2710 of an opening paren which is placed on a new line by that
2711 parameter. The indentation is as follows:
2712
2713 -bbpi=0 one continuation level [default]
2714 -bbpi=1 outdent by one continuation level
2715 -bbpi=2 indent one full indentation level
2716
2717 -bfvt=n, --brace-follower-vertical-tightness=n
2718 Some types of closing block braces, such as eval, may be followed
2719 by additional code. A line break may be inserted between such a
2720 closing brace and the following code depending on the parameter n
2721 and the length of the trailing code, as follows:
2722
2723 If the trailing code fits on a single line, then
2724
2725 -bfvt=0 Follow the input style regarding break/no-break
2726 -bfvt=1 Follow the input style regarding break/no-break [Default]
2727 -bfvt=2 Do not insert a line break
2728
2729 If the trailing code requires multiple lines, then
2730
2731 -bfvt=0 Insert a line break
2732 -bfvt=1 Insert a line break except for a cuddled block chain [Default]
2733 -bfvt=2 Do not insert a line break
2734
2735 So the most compact code is achieved with -bfvt=2.
2736
2737 Example (non-cuddled, multiple lines ):
2738
2739 # -bfvt=0 or -bvft=1 [DEFAULT]
2740 eval {
2741 ( $line, $cond ) = $self->_normalize_if_elif($line);
2742 1;
2743 }
2744 or die sprintf "Error at line %d\nLine %d: %s\n%s",
2745 ( $line_info->start_line_num() ) x 2, $line, $@;
2746
2747 # -bfvt=2
2748 eval {
2749 ( $line, $cond ) = $self->_normalize_if_elif($line);
2750 1;
2751 } or die sprintf "Error at line %d\nLine %d: %s\n%s",
2752 ( $line_info->start_line_num() ) x 2, $line, $@;
2753
2754 Example (cuddled, multiple lines):
2755
2756 # -bfvt=0
2757 eval {
2758 #STUFF;
2759 1; # return true
2760 }
2761 or do {
2762 ##handle error
2763 };
2764
2765 # -bfvt=1 [DEFAULT] or -bfvt=2
2766 eval {
2767 #STUFF;
2768 1; # return true
2769 } or do {
2770 ##handle error
2771 };
2772
2773 Welding
2774 -wn, --weld-nested-containers
2775 The -wn flag causes closely nested pairs of opening and closing
2776 container symbols (curly braces, brackets, or parens) to be
2777 "welded" together, meaning that they are treated as if combined
2778 into a single unit, with the indentation of the innermost code
2779 reduced to be as if there were just a single container symbol.
2780
2781 For example:
2782
2783 # default formatting
2784 do {
2785 {
2786 next if $x == $y;
2787 }
2788 } until $x++ > $z;
2789
2790 # perltidy -wn
2791 do { {
2792 next if $x == $y;
2793 } } until $x++ > $z;
2794
2795 When this flag is set perltidy makes a preliminary pass through the
2796 file and identifies all nested pairs of containers. To qualify as
2797 a nested pair, the closing container symbols must be immediately
2798 adjacent and the opening symbols must either (1) be adjacent as in
2799 the above example, or (2) have an anonymous sub declaration
2800 following an outer opening container symbol which is not a code
2801 block brace, or (3) have an outer opening paren separated from the
2802 inner opening symbol by any single non-container symbol or
2803 something that looks like a function evaluation, as illustrated in
2804 the next examples. An additional option (4) which can be turned on
2805 with the flag --weld-fat-comma is when the opening container
2806 symbols are separated by a hash key and fat comma (=>).
2807
2808 Any container symbol may serve as both the inner container of one
2809 pair and as the outer container of an adjacent pair. Consequently,
2810 any number of adjacent opening or closing symbols may join together
2811 in weld. For example, here are three levels of wrapped function
2812 calls:
2813
2814 # default formatting
2815 my (@date_time) = Localtime(
2816 Date_to_Time(
2817 Add_Delta_DHMS(
2818 $year, $month, $day, $hour, $minute, $second,
2819 '0', $offset, '0', '0'
2820 )
2821 )
2822 );
2823
2824 # perltidy -wn
2825 my (@date_time) = Localtime( Date_to_Time( Add_Delta_DHMS(
2826 $year, $month, $day, $hour, $minute, $second,
2827 '0', $offset, '0', '0'
2828 ) ) );
2829
2830 Notice how the indentation of the inner lines are reduced by two
2831 levels in this case. This example also shows the typical result of
2832 this formatting, namely it is a sandwich consisting of an initial
2833 opening layer, a central section of any complexity forming the
2834 "meat" of the sandwich, and a final closing layer. This
2835 predictable structure helps keep the compacted structure readable.
2836
2837 The inner sandwich layer is required to be at least one line thick.
2838 If this cannot be achieved, welding does not occur. This
2839 constraint can cause formatting to take a couple of iterations to
2840 stabilize when it is first applied to a script. The -conv flag can
2841 be used to insure that the final format is achieved in a single
2842 run.
2843
2844 Here is an example illustrating a welded container within a welded
2845 containers:
2846
2847 # default formatting
2848 $x->badd(
2849 bmul(
2850 $class->new(
2851 abs(
2852 $sx * int( $xr->numify() ) & $sy * int( $yr->numify() )
2853 )
2854 ),
2855 $m
2856 )
2857 );
2858
2859 # perltidy -wn
2860 $x->badd( bmul(
2861 $class->new( abs(
2862 $sx * int( $xr->numify() ) & $sy * int( $yr->numify() )
2863 ) ),
2864 $m
2865 ) );
2866
2867 The welded closing tokens are by default on a separate line but
2868 this can be modified with the -vtc=n flag (described in the next
2869 section). For example, the same example adding -vtc=2 is
2870
2871 # perltidy -wn -vtc=2
2872 $x->badd( bmul(
2873 $class->new( abs(
2874 $sx * int( $xr->numify() ) & $sy * int( $yr->numify() ) ) ),
2875 $m ) );
2876
2877 This format option is quite general but there are some limitations.
2878
2879 One limitation is that any line length limit still applies and can
2880 cause long welded sections to be broken into multiple lines.
2881
2882 Also, the stacking of containers defined by this flag have priority
2883 over any other container stacking flags. This is because any
2884 welding is done first.
2885
2886 -wfc, --weld-fat-comma
2887 When the -wfc flag is set, along with -wn, perltidy is allowed to
2888 weld an opening paren to an inner opening container when they are
2889 separated by a hash key and fat comma (=>). for example
2890
2891 # perltidy -wn -wfc
2892 elf->call_method( method_name_foo => {
2893 some_arg1 => $foo,
2894 some_other_arg3 => $bar->{'baz'},
2895 } );
2896
2897 This option is off by default.
2898
2899 -wnxl=s, --weld-nested-exclusion-list
2900 The -wnxl=s flag provides some control over the types of containers
2901 which can be welded. The -wn flag by default is "greedy" in
2902 welding adjacent containers. If it welds more types of containers
2903 than desired, this flag provides a capability to reduce the amount
2904 of welding by specifying a list of things which should not be
2905 welded.
2906
2907 The logic in perltidy to apply this is straightforward. As each
2908 container token is being considered for joining a weld, any
2909 exclusion rules are consulted and used to reject the weld if
2910 necessary.
2911
2912 This list is a string with space-separated items. Each item
2913 consists of up to three pieces of information: (1) an optional
2914 position, (2) an optional preceding type, and (3) a container type.
2915
2916 The only required piece of information is a container type, which
2917 is one of '(', '[', '{' or 'q'. The first three of these are
2918 container tokens and the last represents a quoted list. For
2919 example the string
2920
2921 -wnxl='[ { q'
2922
2923 means do NOT include square-brackets, braces, or quotes in any
2924 welds. The only unspecified container is '(', so this string means
2925 that only welds involving parens will be made.
2926
2927 To illustrate, following welded snippet consists of a chain of
2928 three welded containers with types '(' '[' and 'q':
2929
2930 # perltidy -wn
2931 skip_symbols( [ qw(
2932 Perl_dump_fds
2933 Perl_ErrorNo
2934 Perl_GetVars
2935 PL_sys_intern
2936 ) ] );
2937
2938 Even though the qw term uses parens as the quote delimiter, it has
2939 a special type 'q' here. If it appears in a weld it always appears
2940 at the end of the welded chain.
2941
2942 Any of the container types '[', '{', and '(' may be prefixed with a
2943 position indicator which is either '^', to indicate the first token
2944 of a welded sequence, or '.', to indicate an interior token of a
2945 welded sequence. (Since a quoted string 'q' always ends a chain it
2946 does need a position indicator).
2947
2948 For example, if we do not want a sequence of welded containers to
2949 start with a square bracket we could use
2950
2951 -wnxl='^['
2952
2953 In the above snippet, there is a square bracket but it does not
2954 start the chain, so the formatting would be unchanged if it were
2955 formatted with this restriction.
2956
2957 A third optional item of information which can be given is an
2958 alphanumeric letter which is used to limit the selection further
2959 depending on the type of token immediately before the container.
2960 If given, it goes just before the container symbol. The possible
2961 letters are currently 'k', 'K', 'f', 'F', 'w', and 'W', with these
2962 meanings:
2963
2964 'k' matches if the previous nonblank token is a perl built-in keyword (such as 'if', 'while'),
2965 'K' matches if 'k' does not, meaning that the previous token is not a keyword.
2966 'f' matches if the previous token is a function other than a keyword.
2967 'F' matches if 'f' does not.
2968 'w' matches if either 'k' or 'f' match.
2969 'W' matches if 'w' does not.
2970
2971 For example, compare
2972
2973 # perltidy -wn
2974 if ( defined( $_Cgi_Query{
2975 $Config{'methods'}{'authentication'}{'remote'}{'cgi'}{'username'}
2976 } ) )
2977
2978 with
2979
2980 # perltidy -wn -wnxl='^K( {'
2981 if ( defined(
2982 $_Cgi_Query{ $Config{'methods'}{'authentication'}{'remote'}{'cgi'}
2983 {'username'} }
2984 ) )
2985
2986 The first case does maximum welding. In the second case the leading
2987 paren is retained by the rule (it would have been rejected if
2988 preceded by a non-keyword) but the curly brace is rejected by the
2989 rule.
2990
2991 Here are some additional example strings and their meanings:
2992
2993 '^(' - the weld must not start with a paren
2994 '.(' - the second and later tokens may not be parens
2995 '.w(' - the second and later tokens may not keyword or function call parens
2996 '(' - no parens in a weld
2997 '^K(' - exclude a leading paren preceded by a non-keyword
2998 '.k(' - exclude a secondary paren preceded by a keyword
2999 '[ {' - exclude all brackets and braces
3000 '[ ( ^K{' - exclude everything except nested structures like do {{ ... }}
3001
3002 Vertical tightness of non-block curly braces, parentheses, and square
3003 brackets.
3004 These parameters control what shall be called vertical tightness.
3005 Here are the main points:
3006
3007 • Opening tokens (except for block braces) are controlled by
3008 -vt=n, or --vertical-tightness=n, where
3009
3010 -vt=0 always break a line after opening token (default).
3011 -vt=1 do not break unless this would produce more than one
3012 step in indentation in a line.
3013 -vt=2 never break a line after opening token
3014
3015 • You must also use the -lp flag when you use the -vt flag; the
3016 reason is explained below.
3017
3018 • Closing tokens (except for block braces) are controlled by
3019 -vtc=n, or --vertical-tightness-closing=n, where
3020
3021 -vtc=0 always break a line before a closing token (default),
3022 -vtc=1 do not break before a closing token which is followed
3023 by a semicolon or another closing token, and is not in
3024 a list environment.
3025 -vtc=2 never break before a closing token.
3026 -vtc=3 Like -vtc=1 except always break before a closing token
3027 if the corresponding opening token follows an = or =>.
3028
3029 The rules for -vtc=1 and -vtc=3 are designed to maintain a
3030 reasonable balance between tightness and readability in complex
3031 lists.
3032
3033 • Different controls may be applied to different token types, and
3034 it is also possible to control block braces; see below.
3035
3036 • Finally, please note that these vertical tightness flags are
3037 merely hints to the formatter, and it cannot always follow
3038 them. Things which make it difficult or impossible include
3039 comments, blank lines, blocks of code within a list, and
3040 possibly the lack of the -lp parameter. Also, these flags may
3041 be ignored for very small lists (2 or 3 lines in length).
3042
3043 Here are some examples:
3044
3045 # perltidy -lp -vt=0 -vtc=0
3046 %romanNumerals = (
3047 one => 'I',
3048 two => 'II',
3049 three => 'III',
3050 four => 'IV',
3051 );
3052
3053 # perltidy -lp -vt=1 -vtc=0
3054 %romanNumerals = ( one => 'I',
3055 two => 'II',
3056 three => 'III',
3057 four => 'IV',
3058 );
3059
3060 # perltidy -lp -vt=1 -vtc=1
3061 %romanNumerals = ( one => 'I',
3062 two => 'II',
3063 three => 'III',
3064 four => 'IV', );
3065
3066 # perltidy -vtc=3
3067 my_function(
3068 one => 'I',
3069 two => 'II',
3070 three => 'III',
3071 four => 'IV', );
3072
3073 # perltidy -vtc=3
3074 %romanNumerals = (
3075 one => 'I',
3076 two => 'II',
3077 three => 'III',
3078 four => 'IV',
3079 );
3080
3081 In the last example for -vtc=3, the opening paren is preceded by an
3082 equals so the closing paren is placed on a new line.
3083
3084 The difference between -vt=1 and -vt=2 is shown here:
3085
3086 # perltidy -lp -vt=1
3087 $init->add(
3088 mysprintf( "(void)find_threadsv(%s);",
3089 cstring( $threadsv_names[ $op->targ ] )
3090 )
3091 );
3092
3093 # perltidy -lp -vt=2
3094 $init->add( mysprintf( "(void)find_threadsv(%s);",
3095 cstring( $threadsv_names[ $op->targ ] )
3096 )
3097 );
3098
3099 With -vt=1, the line ending in "add(" does not combine with the
3100 next line because the next line is not balanced. This can help
3101 with readability, but -vt=2 can be used to ignore this rule.
3102
3103 The tightest, and least readable, code is produced with both
3104 "-vt=2" and "-vtc=2":
3105
3106 # perltidy -lp -vt=2 -vtc=2
3107 $init->add( mysprintf( "(void)find_threadsv(%s);",
3108 cstring( $threadsv_names[ $op->targ ] ) ) );
3109
3110 Notice how the code in all of these examples collapses vertically
3111 as -vt increases, but the indentation remains unchanged. This is
3112 because perltidy implements the -vt parameter by first formatting
3113 as if -vt=0, and then simply overwriting one output line on top of
3114 the next, if possible, to achieve the desired vertical tightness.
3115 The -lp indentation style has been designed to allow this vertical
3116 collapse to occur, which is why it is required for the -vt
3117 parameter.
3118
3119 The -vt=n and -vtc=n parameters apply to each type of container
3120 token. If desired, vertical tightness controls can be applied
3121 independently to each of the closing container token types.
3122
3123 The parameters for controlling parentheses are -pvt=n or
3124 --paren-vertical-tightness=n, and -pvtc=n or
3125 --paren-vertical-tightness-closing=n.
3126
3127 Likewise, the parameters for square brackets are -sbvt=n or
3128 --square-bracket-vertical-tightness=n, and -sbvtc=n or
3129 --square-bracket-vertical-tightness-closing=n.
3130
3131 Finally, the parameters for controlling non-code block braces are
3132 -bvt=n or --brace-vertical-tightness=n, and -bvtc=n or
3133 --brace-vertical-tightness-closing=n.
3134
3135 In fact, the parameter -vt=n is actually just an abbreviation for
3136 -pvt=n -bvt=n sbvt=n, and likewise -vtc=n is an abbreviation for
3137 -pvtc=n -bvtc=n -sbvtc=n.
3138
3139 -bbvt=n or --block-brace-vertical-tightness=n
3140 The -bbvt=n flag is just like the -vt=n flag but applies to opening
3141 code block braces.
3142
3143 -bbvt=0 break after opening block brace (default).
3144 -bbvt=1 do not break unless this would produce more than one
3145 step in indentation in a line.
3146 -bbvt=2 do not break after opening block brace.
3147
3148 It is necessary to also use either -bl or -bli for this to work,
3149 because, as with other vertical tightness controls, it is
3150 implemented by simply overwriting a line ending with an opening
3151 block brace with the subsequent line. For example:
3152
3153 # perltidy -bli -bbvt=0
3154 if ( open( FILE, "< $File" ) )
3155 {
3156 while ( $File = <FILE> )
3157 {
3158 $In .= $File;
3159 $count++;
3160 }
3161 close(FILE);
3162 }
3163
3164 # perltidy -bli -bbvt=1
3165 if ( open( FILE, "< $File" ) )
3166 { while ( $File = <FILE> )
3167 { $In .= $File;
3168 $count++;
3169 }
3170 close(FILE);
3171 }
3172
3173 By default this applies to blocks associated with keywords if,
3174 elsif, else, unless, for, foreach, sub, while, until, and also with
3175 a preceding label. This can be changed with the parameter
3176 -bbvtl=string, or --block-brace-vertical-tightness-list=string,
3177 where string is a space-separated list of block types. For more
3178 information on the possible values of this string, see "Specifying
3179 Block Types"
3180
3181 For example, if we want to just apply this style to "if", "elsif",
3182 and "else" blocks, we could use "perltidy -bli -bbvt=1 -bbvtl='if
3183 elsif else'".
3184
3185 There is no vertical tightness control for closing block braces;
3186 with one exception they will be placed on separate lines. The
3187 exception is that a cascade of closing block braces may be stacked
3188 on a single line. See -scbb.
3189
3190 -sot, --stack-opening-tokens and related flags
3191 The -sot flag tells perltidy to "stack" opening tokens when
3192 possible to avoid lines with isolated opening tokens.
3193
3194 For example:
3195
3196 # default
3197 $opt_c = Text::CSV_XS->new(
3198 {
3199 binary => 1,
3200 sep_char => $opt_c,
3201 always_quote => 1,
3202 }
3203 );
3204
3205 # -sot
3206 $opt_c = Text::CSV_XS->new( {
3207 binary => 1,
3208 sep_char => $opt_c,
3209 always_quote => 1,
3210 }
3211 );
3212
3213 For detailed control of individual closing tokens the following
3214 controls can be used:
3215
3216 -sop or --stack-opening-paren
3217 -sohb or --stack-opening-hash-brace
3218 -sosb or --stack-opening-square-bracket
3219 -sobb or --stack-opening-block-brace
3220
3221 The flag -sot is an abbreviation for -sop -sohb -sosb.
3222
3223 The flag -sobb is an abbreviation for -bbvt=2 -bbvtl='*'. This
3224 will case a cascade of opening block braces to appear on a single
3225 line, although this an uncommon occurrence except in test scripts.
3226
3227 -sct, --stack-closing-tokens and related flags
3228 The -sct flag tells perltidy to "stack" closing tokens when
3229 possible to avoid lines with isolated closing tokens.
3230
3231 For example:
3232
3233 # default
3234 $opt_c = Text::CSV_XS->new(
3235 {
3236 binary => 1,
3237 sep_char => $opt_c,
3238 always_quote => 1,
3239 }
3240 );
3241
3242 # -sct
3243 $opt_c = Text::CSV_XS->new(
3244 {
3245 binary => 1,
3246 sep_char => $opt_c,
3247 always_quote => 1,
3248 } );
3249
3250 The -sct flag is somewhat similar to the -vtc flags, and in some
3251 cases it can give a similar result. The difference is that the
3252 -vtc flags try to avoid lines with leading opening tokens by
3253 "hiding" them at the end of a previous line, whereas the -sct flag
3254 merely tries to reduce the number of lines with isolated closing
3255 tokens by stacking them but does not try to hide them. For
3256 example:
3257
3258 # -vtc=2
3259 $opt_c = Text::CSV_XS->new(
3260 {
3261 binary => 1,
3262 sep_char => $opt_c,
3263 always_quote => 1, } );
3264
3265 For detailed control of the stacking of individual closing tokens
3266 the following controls can be used:
3267
3268 -scp or --stack-closing-paren
3269 -schb or --stack-closing-hash-brace
3270 -scsb or --stack-closing-square-bracket
3271 -scbb or --stack-closing-block-brace
3272
3273 The flag -sct is an abbreviation for stacking the non-block closing
3274 tokens, -scp -schb -scsb.
3275
3276 Stacking of closing block braces, -scbb, causes a cascade of
3277 isolated closing block braces to be combined into a single line as
3278 in the following example:
3279
3280 # -scbb:
3281 for $w1 (@w1) {
3282 for $w2 (@w2) {
3283 for $w3 (@w3) {
3284 for $w4 (@w4) {
3285 push( @lines, "$w1 $w2 $w3 $w4\n" );
3286 } } } }
3287
3288 To simplify input even further for the case in which both opening
3289 and closing non-block containers are stacked, the flag -sac or
3290 --stack-all-containers is an abbreviation for -sot -sct.
3291
3292 Please note that if both opening and closing tokens are to be
3293 stacked, then the newer flag -weld-nested-containers may be
3294 preferable because it insures that stacking is always done
3295 symmetrically. It also removes an extra level of unnecessary
3296 indentation within welded containers. It is able to do this
3297 because it works on formatting globally rather than locally, as the
3298 -sot and -sct flags do.
3299
3300 Breaking Before or After Operators
3301 Four command line parameters provide some control over whether a line
3302 break should be before or after specific token types. Two parameters
3303 give detailed control:
3304
3305 -wba=s or --want-break-after=s, and
3306
3307 -wbb=s or --want-break-before=s.
3308
3309 These parameters are each followed by a quoted string, s, containing a
3310 list of token types (separated only by spaces). No more than one of
3311 each of these parameters should be specified, because repeating a
3312 command-line parameter always overwrites the previous one before
3313 perltidy ever sees it.
3314
3315 By default, perltidy breaks after these token types:
3316 % + - * / x != == >= <= =~ !~ < > | &
3317 = **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x=
3318
3319 And perltidy breaks before these token types by default:
3320 . << >> -> && || //
3321
3322 To illustrate, to cause a break after a concatenation operator, '.',
3323 rather than before it, the command line would be
3324
3325 -wba="."
3326
3327 As another example, the following command would cause a break before
3328 math operators '+', '-', '/', and '*':
3329
3330 -wbb="+ - / *"
3331
3332 These commands should work well for most of the token types that
3333 perltidy uses (use --dump-token-types for a list). Also try the -D
3334 flag on a short snippet of code and look at the .DEBUG file to see the
3335 tokenization. However, for a few token types there may be conflicts
3336 with hardwired logic which cause unexpected results. One example is
3337 curly braces, which should be controlled with the parameter bl provided
3338 for that purpose.
3339
3340 WARNING Be sure to put these tokens in quotes to avoid having them
3341 misinterpreted by your command shell.
3342
3343 Two additional parameters are available which, though they provide no
3344 further capability, can simplify input are:
3345
3346 -baao or --break-after-all-operators,
3347
3348 -bbao or --break-before-all-operators.
3349
3350 The -baao sets the default to be to break after all of the following
3351 operators:
3352
3353 % + - * / x != == >= <= =~ !~ < > | &
3354 = **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x=
3355 . : ? && || and or err xor
3356
3357 and the -bbao flag sets the default to break before all of these
3358 operators. These can be used to define an initial break preference
3359 which can be fine-tuned with the -wba and -wbb flags. For example, to
3360 break before all operators except an = one could use --bbao -wba='='
3361 rather than listing every single perl operator except = on a -wbb flag.
3362
3363 -bal=n, --break-after-labels=n
3364 This flag controls whether or not a line break occurs after a
3365 label. There are three possible values for n:
3366
3367 -bal=0 break if there is a break in the input [DEFAULT]
3368 -bal=1 always break after a label
3369 -bal=2 never break after a label
3370
3371 For example,
3372
3373 # perltidy -bal=1
3374 RETURN:
3375 return;
3376
3377 # perltidy -bal=2
3378 RETURN: return;
3379
3380 Controlling List Formatting
3381 Perltidy attempts to format lists of comma-separated values in tables
3382 which look good. Its default algorithms usually work well, but
3383 sometimes they don't. In this case, there are several methods
3384 available to control list formatting.
3385
3386 A very simple way to prevent perltidy from changing the line breaks
3387 within a comma-separated list of values is to insert a blank line,
3388 comment, or side-comment anywhere between the opening and closing
3389 parens (or braces or brackets). This causes perltidy to skip over its
3390 list formatting logic. (The reason is that any of these items put a
3391 constraint on line breaks, and perltidy needs complete control over
3392 line breaks within a container to adjust a list layout). For example,
3393 let us consider
3394
3395 my @list = (1,
3396 1, 1,
3397 1, 2, 1,
3398 1, 3, 3, 1,
3399 1, 4, 6, 4, 1,);
3400
3401 The default formatting, which allows a maximum line length of 80, will
3402 flatten this down to one line:
3403
3404 # perltidy (default)
3405 my @list = ( 1, 1, 1, 1, 2, 1, 1, 3, 3, 1, 1, 4, 6, 4, 1, );
3406
3407 This formatting loses the nice structure. If we place a side comment
3408 anywhere between the opening and closing parens, the original line
3409 break points are retained. For example,
3410
3411 my @list = (
3412 1, # a side comment forces the original line breakpoints to be kept
3413 1, 1,
3414 1, 2, 1,
3415 1, 3, 3, 1,
3416 1, 4, 6, 4, 1,
3417 );
3418
3419 The side comment can be a single hash symbol without any text. We
3420 could achieve the same result with a blank line or full comment
3421 anywhere between the opening and closing parens. Vertical alignment of
3422 the list items will still occur if possible.
3423
3424 For another possibility see the -fs flag in "Skipping Selected Sections
3425 of Code".
3426
3427 -boc, --break-at-old-comma-breakpoints
3428 The -boc flag is another way to prevent comma-separated lists from
3429 being reformatted. Using -boc on the above example, plus
3430 additional flags to retain the original style, yields
3431
3432 # perltidy -boc -lp -pt=2 -vt=1 -vtc=1
3433 my @list = (1,
3434 1, 1,
3435 1, 2, 1,
3436 1, 3, 3, 1,
3437 1, 4, 6, 4, 1,);
3438
3439 A disadvantage of this flag compared to the methods discussed above
3440 is that all tables in the file must already be nicely formatted.
3441
3442 -mft=n, --maximum-fields-per-table=n
3443 If n is a positive number, and the computed number of fields for
3444 any table exceeds n, then it will be reduced to n. This parameter
3445 might be used on a small section of code to force a list to have a
3446 particular number of fields per line, and then either the -boc flag
3447 could be used to retain this formatting, or a single comment could
3448 be introduced somewhere to freeze the formatting in future
3449 applications of perltidy. For example
3450
3451 # perltidy -mft=2
3452 @month_of_year = (
3453 'Jan', 'Feb',
3454 'Mar', 'Apr',
3455 'May', 'Jun',
3456 'Jul', 'Aug',
3457 'Sep', 'Oct',
3458 'Nov', 'Dec'
3459 );
3460
3461 The default value is n=0, which does not place a limit on the
3462 number of fields in a table.
3463
3464 -cab=n, --comma-arrow-breakpoints=n
3465 A comma which follows a comma arrow, '=>', is given special
3466 consideration. In a long list, it is common to break at all such
3467 commas. This parameter can be used to control how perltidy breaks
3468 at these commas. (However, it will have no effect if old comma
3469 breaks are being forced because -boc is used). The possible values
3470 of n are:
3471
3472 n=0 break at all commas after =>
3473 n=1 stable: break at all commas after => if container is open,
3474 EXCEPT FOR one-line containers
3475 n=2 break at all commas after =>, BUT try to form the maximum
3476 one-line container lengths
3477 n=3 do not treat commas after => specially at all
3478 n=4 break everything: like n=0 but ALSO break a short container with
3479 a => not followed by a comma when -vt=0 is used
3480 n=5 stable: like n=1 but ALSO break at open one-line containers when
3481 -vt=0 is used (default)
3482
3483 For example, given the following single line, perltidy by default
3484 will not add any line breaks because it would break the existing
3485 one-line container:
3486
3487 bless { B => $B, Root => $Root } => $package;
3488
3489 Using -cab=0 will force a break after each comma-arrow item:
3490
3491 # perltidy -cab=0:
3492 bless {
3493 B => $B,
3494 Root => $Root
3495 } => $package;
3496
3497 If perltidy is subsequently run with this container broken, then by
3498 default it will break after each '=>' because the container is now
3499 broken. To reform a one-line container, the parameter -cab=2 could
3500 be used.
3501
3502 The flag -cab=3 can be used to prevent these commas from being
3503 treated specially. In this case, an item such as "01" => 31 is
3504 treated as a single item in a table. The number of fields in this
3505 table will be determined by the same rules that are used for any
3506 other table. Here is an example.
3507
3508 # perltidy -cab=3
3509 my %last_day = (
3510 "01" => 31, "02" => 29, "03" => 31, "04" => 30,
3511 "05" => 31, "06" => 30, "07" => 31, "08" => 31,
3512 "09" => 30, "10" => 31, "11" => 30, "12" => 31
3513 );
3514
3515 Adding and Deleting Commas
3516 -drc, --delete-repeated-commas
3517 Repeated commas in a list are undesirable and can be removed with
3518 this flag. For example, given this list with a repeated comma
3519
3520 ignoreSpec( $file, "file",, \%spec, \%Rspec );
3521
3522 we can remove it with -drc
3523
3524 # perltidy -drc:
3525 ignoreSpec( $file, "file", \%spec, \%Rspec );
3526
3527 Since the default is not to add or delete commas, this feature is
3528 off by default and must be requested.
3529
3530 --want-trailing-commas=s or -wtc=s, --add-trailing-commas or -atc, and
3531 --delete-trailing-commas or -dtc
3532 A trailing comma is a comma following the last item of a list. Perl
3533 allows trailing commas but they are not required. By default,
3534 perltidy does not add or delete trailing commas, but it is possible
3535 to manipulate them with the following set of three related
3536 parameters:
3537
3538 --want-trailing-commas=s, -wtc=s - defines where trailing commas are wanted
3539 --add-trailing-commas, -atc - gives permission to add trailing commas to match the style wanted
3540 --delete-trailing-commas, -dtc - gives permission to delete trailing commas which do not match the style wanted
3541
3542 The parameter --want-trailing-commas=s, or -wtc=s, defines a
3543 preferred style. The string s indicates which lists should get
3544 trailing commas, as follows:
3545
3546 s=0 : no list should have a trailing comma
3547 s=1 or * : every list should have a trailing comma
3548 s=m a multi-line list should have a trailing commas
3549 s=b trailing commas should be 'bare' (comma followed by newline)
3550 s=h lists of key=>value pairs, with about one one '=>' and one ',' per line,
3551 with a bare trailing comma
3552 s=i lists with about one comma per line, with a bare trailing comma
3553 s=' ' or -wtc not defined : leave trailing commas unchanged [DEFAULT].
3554
3555 This parameter by itself only indicates the where trailing commas
3556 are wanted. Perltidy only adds these trailing commas if the flag
3557 --add-trailing-commas, or -atc is set. And perltidy only removes
3558 unwanted trailing commas if the flag --delete-trailing-commas, or
3559 -dtc is set.
3560
3561 Here are some example parameter combinations and their meanings
3562
3563 -wtc=0 -dtc : delete all trailing commas
3564 -wtc=1 -atc : all lists get trailing commas
3565 -wtc=m -atc : all multi-line lists get trailing commas, but
3566 single line lists remain unchanged.
3567 -wtc=m -dtc : multi-line lists remain unchanged, but
3568 any trailing commas on single line lists are removed.
3569 -wtc=m -atc -dtc : all multi-line lists get trailing commas, and
3570 any trailing commas on single line lists are removed.
3571
3572 For example, given the following input without a trailing comma
3573
3574 bless {
3575 B => $B,
3576 Root => $Root
3577 } => $package;
3578
3579 we can add a trailing comma after the variable $Root using
3580
3581 # perltidy -wtc=m -atc
3582 bless {
3583 B => $B,
3584 Root => $Root,
3585 } => $package;
3586
3587 This could also be achieved in this case with -wtc=b instead of
3588 -wtc=m because the trailing comma here is bare (separated from its
3589 closing brace by a newline). And it could also be achieved with
3590 -wtc=h because this particular list is a list of key=>value pairs.
3591
3592 The above styles should cover the main of situations of interest,
3593 but it is possible to apply a different style to each type of
3594 container token by including an opening token ahead of the style
3595 character in the above table. For example
3596
3597 -wtc='(m [b'
3598
3599 means that lists within parens should have multi-line trailing
3600 commas, and that lists within square brackets have bare trailing
3601 commas. Since there is no specification for curly braces in this
3602 example, their trailing commas would remain unchanged.
3603
3604 For parentheses, an additional item of information which can be
3605 given is an alphanumeric letter which is used to limit the
3606 selection further depending on the type of token immediately before
3607 the opening paren. The possible letters are currently 'k', 'K',
3608 'f', 'F', 'w', and 'W', with these meanings for matching whatever
3609 precedes an opening paren:
3610
3611 'k' matches if the previous nonblank token is a perl built-in keyword (such as 'if', 'while'),
3612 'K' matches if 'k' does not, meaning that the previous token is not a keyword.
3613 'f' matches if the previous token is a function other than a keyword.
3614 'F' matches if 'f' does not.
3615 'w' matches if either 'k' or 'f' match.
3616 'W' matches if 'w' does not.
3617
3618 These are the same codes used for
3619 --line-up-parentheses-inclusion-list. For example,
3620
3621 -wtc = 'w(m'
3622
3623 means that trailing commas are wanted for multi-line parenthesized
3624 lists following a function call or keyword.
3625
3626 Here are some points to note regarding adding and deleting trailing
3627 commas:
3628
3629 • For the implementation of these parameters, a list is basically
3630 taken to be a container of items (parens, square brackets, or
3631 braces), which is not a code block, with one or more commas.
3632 These parameters only apply to something that fits this
3633 definition of a list.
3634
3635 Note that a paren-less list of parameters is not a list by this
3636 definition, so these parameters have no effect on a paren-less
3637 list.
3638
3639 Another consequence is that if the only comma in a list is
3640 deleted, then it cannot later be added back with these
3641 parameters because the container no longer fits this definition
3642 of a list. For example, given
3643
3644 my ( $self, ) = @_;
3645
3646 and if we remove the comma with
3647
3648 # perltidy -wtc=m -dtc
3649 my ( $self ) = @_;
3650
3651 then we cannot use these trailing comma controls to add this
3652 comma back.
3653
3654 • By multiline list is meant a list for which the first comma and
3655 trailing comma are on different lines.
3656
3657 • A bare trailing comma is a comma which is at the end of a line.
3658 That is, the closing container token follows on a different
3659 line. So a list with a bare trailing comma is a special case
3660 of a multi-line list.
3661
3662 • The decision regarding whether or not a list is multi-line or
3663 bare is made based on the input stream. In some cases it may
3664 take an iteration or two to reach a final state.
3665
3666 • When using these parameters for the first time it is a good
3667 idea to practice on some test scripts and verify that the
3668 results are as expected.
3669
3670 • Since the default behavior is not to add or delete commas,
3671 these parameters can be useful on a temporary basis for
3672 reformatting a script.
3673
3674 -dwic, --delete-weld-interfering-commas
3675 If the closing tokens of two nested containers are separated by a
3676 comma, then welding requested with --weld-nested-containers cannot
3677 occur. Any commas in this situation are optional trailing commas
3678 and can be removed with -dwic. For example, a comma in this script
3679 prevents welding:
3680
3681 # perltidy -wn
3682 skip_symbols(
3683 [ qw(
3684 Perl_dump_fds
3685 Perl_ErrorNo
3686 Perl_GetVars
3687 PL_sys_intern
3688 ) ],
3689 );
3690
3691 Using -dwic removes the comma and allows welding:
3692
3693 # perltidy -wn -dwic
3694 skip_symbols( [ qw(
3695 Perl_dump_fds
3696 Perl_ErrorNo
3697 Perl_GetVars
3698 PL_sys_intern
3699 ) ] );
3700
3701 Since the default is not to add or delete commas, this feature is
3702 off by default. Here are some points to note about the -dwic
3703 parameter
3704
3705 • This operation is not reversible, so please check results of
3706 using this parameter carefully.
3707
3708 • Removing this type of isolated trailing comma is necessary for
3709 welding to be possible, but not sufficient. So welding will
3710 not always occur where these commas are removed.
3711
3712 Missing Else Blocks
3713 A defensive programming technique is to require that every if-elsif-
3714 chain be terminated with an else block, even though it is not strictly
3715 required. This helps insure that there are no holes in the logic.
3716
3717 For example, consider the following snippet:
3718
3719 my $type = get_cards();
3720 if ( $type = 1 ) { action("hold 'em") }
3721 elsif ( $type = 2 ) { action("fold 'em") }
3722 elsif ( $type = 3 ) { action("walk away") }
3723
3724 What if the variable $type is some other value? It might have been
3725 obvious that this was okay when the code was first written, but it
3726 might not be so clear when the code is reviewed a few years later. A
3727 terminal else block with a comment would help clarify things.
3728
3729 The parameters in this section can help by either issuing a warning if
3730 an else is missing, or even inserting an empty else block where one is
3731 missing, or both.
3732
3733 -wme, --warn-missing-else
3734 This flag tells perltidy to issue a warning if a program is missing
3735 a terminal else block. The default is not to issue such a warning.
3736
3737 -ame, --add-missing-else
3738 This flag tells perltidy to output an empty else block wherever a
3739 program is missing a terminal else block. To get a warning when
3740 this is done you should also set -wme. The default is not to add
3741 missing else blocks.
3742
3743 -amec=s, --add-missing-else-comment=s
3744 This string is a side comment which will be written to highlight a
3745 new empty else block. The default is:
3746
3747 -amec='##FIXME - added with perltidy -ame'
3748
3749 For example, on the above example we can add a missing else and also
3750 get a warning notice with:
3751
3752 # perltidy -ame -wme
3753 my $type = get_cards();
3754 if ( $type == 1 ) { action("hold 'em") }
3755 elsif ( $type == 2 ) { action("fold 'em") }
3756 elsif ( $type == 3 ) { action("walk away") }
3757 else {
3758 ##FIXME - added with perltidy -ame
3759 }
3760
3761 Any ##FIXME comments created in this way should be reviewed and changed
3762 appropriately. For example, one might decide that the code fine as is,
3763 and just change the comment to indicate that nothing has been
3764 overlooked:
3765
3766 my $type = get_cards();
3767 if ( $type == 1 ) { action("hold 'em") }
3768 elsif ( $type == 2 ) { action("fold 'em") }
3769 elsif ( $type == 3 ) { action("walk away") }
3770 else {
3771 # ok - no worries
3772 }
3773
3774 Or maybe a deeper analysis reveals that something was missed:
3775
3776 my $type = get_cards();
3777 if ( $type == 1 ) { action("hold 'em") }
3778 elsif ( $type == 2 ) { action("fold 'em") }
3779 elsif ( $type == 3 ) { action("walk away") }
3780 else { action("run") }
3781
3782 Sometimes it turns out that the else block should not reachable, in
3783 which case an error exit might be appropriate. In any case, having the
3784 else block can improve code maintainability.
3785
3786 Retaining or Ignoring Existing Line Breaks
3787 Several additional parameters are available for controlling the extent
3788 to which line breaks in the input script influence the output script.
3789 In most cases, the default parameter values are set so that, if a
3790 choice is possible, the output style follows the input style. For
3791 example, if a short logical container is broken in the input script,
3792 then the default behavior is for it to remain broken in the output
3793 script.
3794
3795 Most of the parameters in this section would only be required for a
3796 one-time conversion of a script from short container lengths to longer
3797 container lengths. The opposite effect, of converting long container
3798 lengths to shorter lengths, can be obtained by temporarily using a
3799 short maximum line length.
3800
3801 -bol, --break-at-old-logical-breakpoints
3802 By default, if a logical expression is broken at a "&&", "||",
3803 "and", or "or", then the container will remain broken. Also,
3804 breaks at internal keywords "if" and "unless" will normally be
3805 retained. To prevent this, and thus form longer lines, use -nbol.
3806
3807 Please note that this flag does not duplicate old logical
3808 breakpoints. They are merely used as a hint with this flag that a
3809 statement should remain broken. Without this flag, perltidy will
3810 normally try to combine relatively short expressions into a single
3811 line.
3812
3813 For example, given this snippet:
3814
3815 return unless $cmd = $cmd || ($dot
3816 && $Last_Shell) || &prompt('|');
3817
3818 # perltidy -bol [default]
3819 return
3820 unless $cmd = $cmd
3821 || ( $dot
3822 && $Last_Shell )
3823 || &prompt('|');
3824
3825 # perltidy -nbol
3826 return unless $cmd = $cmd || ( $dot && $Last_Shell ) || &prompt('|');
3827
3828 -bom, --break-at-old-method-breakpoints
3829 By default, a method call arrow "->" is considered a candidate for
3830 a breakpoint, but method chains will fill to the line width before
3831 a break is considered. With -bom, breaks before the arrow are
3832 preserved, so if you have pre-formatted a method chain:
3833
3834 my $q = $rs
3835 ->related_resultset('CDs')
3836 ->related_resultset('Tracks')
3837 ->search({
3838 'track.id' => {-ident => 'none_search.id'},
3839 })->as_query;
3840
3841 It will keep these breaks, rather than become this:
3842
3843 my $q = $rs->related_resultset('CDs')->related_resultset('Tracks')->search({
3844 'track.id' => {-ident => 'none_search.id'},
3845 })->as_query;
3846
3847 This flag will also look for and keep a 'cuddled' style of calls,
3848 in which lines begin with a closing paren followed by a call arrow,
3849 as in this example:
3850
3851 # perltidy -bom -wn
3852 my $q = $rs->related_resultset(
3853 'CDs'
3854 )->related_resultset(
3855 'Tracks'
3856 )->search( {
3857 'track.id' => { -ident => 'none_search.id' },
3858 } )->as_query;
3859
3860 You may want to include the -weld-nested-containers flag in this
3861 case to keep nested braces and parens together, as in the last
3862 line.
3863
3864 -bos, --break-at-old-semicolon-breakpoints
3865 Semicolons are normally placed at the end of a statement. This
3866 means that formatted lines do not normally begin with semicolons.
3867 If the input stream has some lines which begin with semicolons,
3868 these can be retained by setting this flag. For example, consider
3869 the following two-line input snippet:
3870
3871 $z = sqrt($x**2 + $y**2)
3872 ;
3873
3874 The default formatting will be:
3875
3876 $z = sqrt( $x**2 + $y**2 );
3877
3878 The result using perltidy -bos keeps the isolated semicolon:
3879
3880 $z = sqrt( $x**2 + $y**2 )
3881 ;
3882
3883 The default is not to do this, -nbos.
3884
3885 -bok, --break-at-old-keyword-breakpoints
3886 By default, perltidy will retain a breakpoint before keywords which
3887 may return lists, such as "sort" and <map>. This allows chains of
3888 these operators to be displayed one per line. Use -nbok to prevent
3889 retaining these breakpoints.
3890
3891 -bot, --break-at-old-ternary-breakpoints
3892 By default, if a conditional (ternary) operator is broken at a ":",
3893 then it will remain broken. To prevent this, and thereby form
3894 longer lines, use -nbot.
3895
3896 -boa, --break-at-old-attribute-breakpoints
3897 By default, if an attribute list is broken at a ":" in the source
3898 file, then it will remain broken. For example, given the following
3899 code, the line breaks at the ':'s will be retained:
3900
3901 my @field
3902 : field
3903 : Default(1)
3904 : Get('Name' => 'foo') : Set('Name');
3905
3906 If the attributes are on a single line in the source code then they
3907 will remain on a single line if possible.
3908
3909 To prevent this, and thereby always form longer lines, use -nboa.
3910
3911 Keeping old breakpoints at specific token types
3912 It is possible to override the choice of line breaks made by
3913 perltidy, and force it to follow certain line breaks in the input
3914 stream, with these two parameters:
3915
3916 -kbb=s or --keep-old-breakpoints-before=s, and
3917
3918 -kba=s or --keep-old-breakpoints-after=s
3919
3920 These parameters are each followed by a quoted string, s,
3921 containing a list of token types (separated only by spaces). No
3922 more than one of each of these parameters should be specified,
3923 because repeating a command-line parameter always overwrites the
3924 previous one before perltidy ever sees it.
3925
3926 For example, -kbb='=>' means that if an input line begins with a
3927 '=>' then the output script should also have a line break before
3928 that token.
3929
3930 For example, given the script:
3931
3932 method 'foo'
3933 => [ Int, Int ]
3934 => sub {
3935 my ( $self, $x, $y ) = ( shift, @_ );
3936 ...;
3937 };
3938
3939 # perltidy [default]
3940 method 'foo' => [ Int, Int ] => sub {
3941 my ( $self, $x, $y ) = ( shift, @_ );
3942 ...;
3943 };
3944
3945 # perltidy -kbb='=>'
3946 method 'foo'
3947 => [ Int, Int ]
3948 => sub {
3949 my ( $self, $x, $y ) = ( shift, @_ );
3950 ...;
3951 };
3952
3953 For the container tokens '{', '[' and '(' and, their closing
3954 counterparts, use the token symbol. Thus, the command to keep a
3955 break after all opening parens is:
3956
3957 perltidy -kba='('
3958
3959 It is possible to be more specific in matching parentheses by
3960 preceding them with a letter. The possible letters are 'k', 'K',
3961 'f', 'F', 'w', and 'W', with these meanings (these are the same as
3962 used in the --weld-nested-exclusion-list and
3963 --line-up-parentheses-exclusion-list parameters):
3964
3965 'k' matches if the previous nonblank token is a perl built-in keyword (such as 'if', 'while'),
3966 'K' matches if 'k' does not, meaning that the previous token is not a keyword.
3967 'f' matches if the previous token is a function other than a keyword.
3968 'F' matches if 'f' does not.
3969 'w' matches if either 'k' or 'f' match.
3970 'W' matches if 'w' does not.
3971
3972 So for example the the following parameter will keep breaks after
3973 opening function call parens:
3974
3975 perltidy -kba='f('
3976
3977 NOTE: A request to break before an opening container, such as
3978 -kbb='(', will be silently ignored because it can lead to
3979 formatting instability. Likewise, a request to break after a
3980 closing container, such as -kba=')', will also be silently ignored.
3981
3982 -iob, --ignore-old-breakpoints
3983 Use this flag to tell perltidy to ignore existing line breaks to
3984 the maximum extent possible. This will tend to produce the longest
3985 possible containers, regardless of type, which do not exceed the
3986 line length limit. But please note that this parameter has
3987 priority over all other parameters requesting that certain old
3988 breakpoints be kept.
3989
3990 To illustrate, consider the following input text:
3991
3992 has subcmds => (
3993 is => 'ro',
3994 default => sub { [] },
3995 );
3996
3997 The default formatting will keep the container broken, giving
3998
3999 # perltidy [default]
4000 has subcmds => (
4001 is => 'ro',
4002 default => sub { [] },
4003 );
4004
4005 If old breakpoints are ignored, the list will be flattened:
4006
4007 # perltidy -iob
4008 has subcmds => ( is => 'ro', default => sub { [] }, );
4009
4010 Besides flattening lists, this parameter also applies to lines
4011 broken at certain logical breakpoints such as 'if' and 'or'.
4012
4013 Even if this is parameter is not used globally, it provides a
4014 convenient way to flatten selected lists from within an editor.
4015
4016 -kis, --keep-interior-semicolons
4017 Use the -kis flag to prevent breaking at a semicolon if there was
4018 no break there in the input file. Normally perltidy places a
4019 newline after each semicolon which terminates a statement unless
4020 several statements are contained within a one-line brace block. To
4021 illustrate, consider the following input lines:
4022
4023 dbmclose(%verb_delim); undef %verb_delim;
4024 dbmclose(%expanded); undef %expanded;
4025
4026 The default is to break after each statement, giving
4027
4028 dbmclose(%verb_delim);
4029 undef %verb_delim;
4030 dbmclose(%expanded);
4031 undef %expanded;
4032
4033 With perltidy -kis the multiple statements are retained:
4034
4035 dbmclose(%verb_delim); undef %verb_delim;
4036 dbmclose(%expanded); undef %expanded;
4037
4038 The statements are still subject to the specified value of maximum-
4039 line-length and will be broken if this maximum is exceeded.
4040
4041 Blank Line Control
4042 Blank lines can improve the readability of a script if they are
4043 carefully placed. Perltidy has several commands for controlling the
4044 insertion, retention, and removal of blank lines.
4045
4046 -fbl, --freeze-blank-lines
4047 Set -fbl if you want to the blank lines in your script to remain
4048 exactly as they are. The rest of the parameters in this section
4049 may then be ignored. (Note: setting the -fbl flag is equivalent to
4050 setting -mbl=0 and -kbl=2).
4051
4052 -bbc, --blanks-before-comments
4053 A blank line will be introduced before a full-line comment. This
4054 is the default. Use -nbbc or --noblanks-before-comments to
4055 prevent such blank lines from being introduced.
4056
4057 -blbs=n, --blank-lines-before-subs=n
4058 The parameter -blbs=n requests that least n blank lines precede a
4059 sub definition which does not follow a comment and which is more
4060 than one-line long. The default is <-blbs=1>. BEGIN and END
4061 blocks are included.
4062
4063 The requested number of blanks statement will be inserted
4064 regardless of the value of --maximum-consecutive-blank-lines=n
4065 (-mbl=n) with the exception that if -mbl=0 then no blanks will be
4066 output.
4067
4068 This parameter interacts with the value k of the parameter
4069 --maximum-consecutive-blank-lines=k (-mbl=k) as follows:
4070
4071 1. If -mbl=0 then no blanks will be output. This allows all blanks
4072 to be suppressed with a single parameter. Otherwise,
4073
4074 2. If the number of old blank lines in the script is less than n
4075 then additional blanks will be inserted to make the total n
4076 regardless of the value of -mbl=k.
4077
4078 3. If the number of old blank lines in the script equals or exceeds
4079 n then this parameter has no effect, however the total will not
4080 exceed value specified on the -mbl=k flag.
4081
4082 -blbp=n, --blank-lines-before-packages=n
4083 The parameter -blbp=n requests that least n blank lines precede a
4084 package which does not follow a comment. The default is -blbp=1.
4085
4086 This parameter interacts with the value k of the parameter
4087 --maximum-consecutive-blank-lines=k (-mbl=k) in the same way as
4088 described for the previous item -blbs=n.
4089
4090 -bbs, --blanks-before-subs
4091 For compatibility with previous versions, -bbs or
4092 --blanks-before-subs is equivalent to -blbp=1 and -blbs=1.
4093
4094 Likewise, -nbbs or --noblanks-before-subs is equivalent to -blbp=0
4095 and -blbs=0.
4096
4097 -bbb, --blanks-before-blocks
4098 A blank line will be introduced before blocks of coding delimited
4099 by for, foreach, while, until, and if, unless, in the following
4100 circumstances:
4101
4102 • The block is not preceded by a comment.
4103
4104 • The block is not a one-line block.
4105
4106 • The number of consecutive non-blank lines at the current
4107 indentation depth is at least -lbl (see next section).
4108
4109 This is the default. The intention of this option is to introduce
4110 some space within dense coding. This is negated with -nbbb or
4111 --noblanks-before-blocks.
4112
4113 -lbl=n --long-block-line-count=n
4114 This controls how often perltidy is allowed to add blank lines
4115 before certain block types (see previous section). The default is
4116 8. Entering a value of 0 is equivalent to entering a very large
4117 number.
4118
4119 -blao=i or --blank-lines-after-opening-block=i
4120 This control places a minimum of i blank lines after a line which
4121 ends with an opening block brace of a specified type. By default,
4122 this only applies to the block of a named sub, but this can be
4123 changed (see -blaol below). The default is not to do this (i=0).
4124
4125 Please see the note below on using the -blao and -blbc options.
4126
4127 -blbc=i or --blank-lines-before-closing-block=i
4128 This control places a minimum of i blank lines before a line which
4129 begins with a closing block brace of a specified type. By default,
4130 this only applies to the block of a named sub, but this can be
4131 changed (see -blbcl below). The default is not to do this (i=0).
4132
4133 -blaol=s or --blank-lines-after-opening-block-list=s
4134 The parameter s is a list of block type keywords to which the flag
4135 -blao should apply. The section "Specifying Block Types" explains
4136 how to list block types.
4137
4138 -blbcl=s or --blank-lines-before-closing-block-list=s
4139 This parameter is a list of block type keywords to which the flag
4140 -blbc should apply. The section "Specifying Block Types" explains
4141 how to list block types.
4142
4143 Note on using the -blao and -blbc options.
4144 These blank line controls introduce a certain minimum number of
4145 blank lines in the text, but the final number of blank lines may be
4146 greater, depending on values of the other blank line controls and
4147 the number of old blank lines. A consequence is that introducing
4148 blank lines with these and other controls cannot be exactly undone,
4149 so some experimentation with these controls is recommended before
4150 using them.
4151
4152 For example, suppose that for some reason we decide to introduce
4153 one blank space at the beginning and ending of all blocks. We
4154 could do this using
4155
4156 perltidy -blao=2 -blbc=2 -blaol='*' -blbcl='*' filename
4157
4158 Now suppose the script continues to be developed, but at some later
4159 date we decide we don't want these spaces after all. We might
4160 expect that running with the flags -blao=0 and -blbc=0 will undo
4161 them. However, by default perltidy retains single blank lines, so
4162 the blank lines remain.
4163
4164 We can easily fix this by telling perltidy to ignore old blank
4165 lines by including the added parameter -kbl=0 and rerunning. Then
4166 the unwanted blank lines will be gone. However, this will cause
4167 all old blank lines to be ignored, perhaps even some that were
4168 added by hand to improve formatting. So please be cautious when
4169 using these parameters.
4170
4171 -mbl=n --maximum-consecutive-blank-lines=n
4172 This parameter specifies the maximum number of consecutive blank
4173 lines which will be output within code sections of a script. The
4174 default is n=1. If the input file has more than n consecutive
4175 blank lines, the number will be reduced to n except as noted above
4176 for the -blbp and -blbs parameters. If n=0 then no blank lines
4177 will be output (unless all old blank lines are retained with the
4178 -kbl=2 flag of the next section).
4179
4180 This flag obviously does not apply to pod sections, here-documents,
4181 and quotes.
4182
4183 -kbl=n, --keep-old-blank-lines=n
4184 The -kbl=n flag gives you control over how your existing blank
4185 lines are treated.
4186
4187 The possible values of n are:
4188
4189 n=0 ignore all old blank lines
4190 n=1 stable: keep old blanks, but limited by the value of the B<-mbl=n> flag
4191 n=2 keep all old blank lines, regardless of the value of the B<-mbl=n> flag
4192
4193 The default is n=1.
4194
4195 -sob, --swallow-optional-blank-lines
4196 This is equivalent to kbl=0 and is included for compatibility with
4197 previous versions.
4198
4199 -nsob, --noswallow-optional-blank-lines
4200 This is equivalent to kbl=1 and is included for compatibility with
4201 previous versions.
4202
4203 Controls for blank lines around lines of consecutive keywords
4204
4205 The parameters in this section provide some control over the placement
4206 of blank lines within and around groups of statements beginning with
4207 selected keywords. These blank lines are called here keyword group
4208 blanks, and all of the parameters begin with --keyword-group-blanks*,
4209 or -kgb* for short. The default settings do not employ these controls
4210 but they can be enabled with the following parameters:
4211
4212 -kgbl=s or --keyword-group-blanks-list=s; s is a quoted string of
4213 keywords
4214
4215 -kgbs=s or --keyword-group-blanks-size=s; s gives the number of
4216 keywords required to form a group.
4217
4218 -kgbb=n or --keyword-group-blanks-before=n; n = (0, 1, or 2) controls a
4219 leading blank
4220
4221 -kgba=n or --keyword-group-blanks-after=n; n = (0, 1, or 2) controls a
4222 trailing blank
4223
4224 -kgbi or --keyword-group-blanks-inside is a switch for adding blanks
4225 between subgroups
4226
4227 -kgbd or --keyword-group-blanks-delete is a switch for removing initial
4228 blank lines between keywords
4229
4230 -kgbr=n or --keyword-group-blanks-repeat-count=n can limit the number
4231 of times this logic is applied
4232
4233 In addition, the following abbreviations are available to for
4234 simplified usage:
4235
4236 -kgb or --keyword-group-blanks is short for -kgbb=2 -kgba=2 kgbi
4237
4238 -nkgb or --nokeyword-group-blanks, is short for -kgbb=1 -kgba=1 nkgbi
4239
4240 Before describing the meaning of the parameters in detail let us look
4241 at an example which is formatted with default parameter settings.
4242
4243 print "Entering test 2\n";
4244 use Test;
4245 use Encode qw(from_to encode decode
4246 encode_utf8 decode_utf8
4247 find_encoding is_utf8);
4248 use charnames qw(greek);
4249 my @encodings = grep( /iso-?8859/, Encode::encodings() );
4250 my @character_set = ( '0' .. '9', 'A' .. 'Z', 'a' .. 'z' );
4251 my @source = qw(ascii iso8859-1 cp1250);
4252 my @destiny = qw(cp1047 cp37 posix-bc);
4253 my @ebcdic_sets = qw(cp1047 cp37 posix-bc);
4254 my $str = join( '', map( chr($_), 0x20 .. 0x7E ) );
4255 return unless ($str);
4256
4257 using perltidy -kgb gives:
4258
4259 print "Entering test 2\n";
4260 <----------this blank controlled by -kgbb
4261 use Test;
4262 use Encode qw(from_to encode decode
4263 encode_utf8 decode_utf8
4264 find_encoding is_utf8);
4265 use charnames qw(greek);
4266 <---------this blank controlled by -kgbi
4267 my @encodings = grep( /iso-?8859/, Encode::encodings() );
4268 my @character_set = ( '0' .. '9', 'A' .. 'Z', 'a' .. 'z' );
4269 my @source = qw(ascii iso8859-1 cp1250);
4270 my @destiny = qw(cp1047 cp37 posix-bc);
4271 my @ebcdic_sets = qw(cp1047 cp37 posix-bc);
4272 my $str = join( '', map( chr($_), 0x20 .. 0x7E ) );
4273 <----------this blank controlled by -kgba
4274 return unless ($str);
4275
4276 Blank lines have been introduced around the my and use sequences. What
4277 happened is that the default keyword list includes my and use but not
4278 print and return. So a continuous sequence of nine my and use
4279 statements was located. This number exceeds the default threshold of
4280 five, so blanks were placed before and after the entire group. Then,
4281 since there was also a subsequence of six my lines, a blank line was
4282 introduced to separate them.
4283
4284 Finer control over blank placement can be achieved by using the
4285 individual parameters rather than the -kgb flag. The individual
4286 controls are as follows.
4287
4288 -kgbl=s or --keyword-group-blanks-list=s, where s is a quoted string,
4289 defines the set of keywords which will be formed into groups. The
4290 string is a space separated list of keywords. The default set is
4291 s="use require local our my", but any list of keywords may be used.
4292 Comment lines may also be included in a keyword group, even though they
4293 are not keywords. To include ordinary block comments, include the
4294 symbol BC. To include static block comments (which normally begin with
4295 '##'), include the symbol SBC.
4296
4297 -kgbs=s or --keyword-group-blanks-size=s, where s is a string
4298 describing the number of consecutive keyword statements forming a group
4299 (Note: statements separated by blank lines in the input file are
4300 considered consecutive for purposes of this count). If s is an integer
4301 then it is the minimum number required for a group. A maximum value
4302 may also be given with the format s=min.max, where min is the minimum
4303 number and max is the maximum number, and the min and max values are
4304 separated by one or more dots. No groups will be found if the maximum
4305 is less than the minimum. The maximum is unlimited if not given. The
4306 default is s=5. Some examples:
4307
4308 s min max number for group
4309 3 3 unlimited 3 or more
4310 1.1 1 1 1
4311 1..3 1 3 1 to 3
4312 1.0 1 0 (no match)
4313
4314 There is no really good default value for this parameter. If it is set
4315 too small, then an excessive number of blank lines may be generated.
4316 However, some users may prefer reducing the value somewhat below the
4317 default, perhaps to s=3.
4318
4319 -kgbb=n or --keyword-group-blanks-before=n specifies whether a blank
4320 should appear before the first line of the group, as follows:
4321
4322 n=0 => (delete) an existing blank line will be removed
4323 n=1 => (stable) no change to the input file is made [DEFAULT]
4324 n=2 => (insert) a blank line is introduced if possible
4325
4326 -kgba=n or --keyword-group-blanks-after=n likewise specifies whether a
4327 blank should appear after the last line of the group, using the same
4328 scheme (0=delete, 1=stable, 2=insert).
4329
4330 -kgbi or --keyword-group-blanks-inside controls the insertion of blank
4331 lines between the first and last statement of the entire group. If
4332 there is a continuous run of a single statement type with more than the
4333 minimum threshold number (as specified with -kgbs=s) then this switch
4334 causes a blank line be inserted between this subgroup and the others.
4335 In the example above this happened between the use and my statements.
4336
4337 -kgbd or --keyword-group-blanks-delete controls the deletion of any
4338 blank lines that exist in the the group when it is first scanned. When
4339 statements are initially scanned, any existing blank lines are included
4340 in the collection. Any such original blank lines will be deleted
4341 before any other insertions are made when the parameter -kgbd is set.
4342 The default is not to do this, -nkgbd.
4343
4344 -kgbr=n or --keyword-group-blanks-repeat-count=n specifies n, the
4345 maximum number of times this logic will be applied to any file. The
4346 special value n=0 is the same as n=infinity which means it will be
4347 applied to an entire script [Default]. A value n=1 could be used to
4348 make it apply just one time for example. This might be useful for
4349 adjusting just the use statements in the top part of a module for
4350 example.
4351
4352 -kgb or --keyword-group-blanks is an abbreviation equivalent to setting
4353 -kgbb=1 -kgba=1 -kgbi. This turns on keyword group formatting with a
4354 set of default values.
4355
4356 -nkgb or --nokeyword-group-blanks is equivalent to -kgbb=0 -kgba nkgbi.
4357 This flag turns off keyword group blank lines and is the default
4358 setting.
4359
4360 Here are a few notes about the functioning of this technique.
4361
4362 • These parameters are probably more useful as part of a major code
4363 reformatting operation rather than as a routine formatting
4364 operation.
4365
4366 In particular, note that deleting old blank lines with -kgbd is an
4367 irreversible operation so it should be applied with care. Existing
4368 blank lines may be serving an important role in controlling
4369 vertical alignment.
4370
4371 • Conflicts which arise among these kgb* parameters and other blank
4372 line controls are generally resolved by producing the maximum
4373 number of blank lines implied by any parameter.
4374
4375 For example, if the flags --freeze-blank-lines, or
4376 --keep-old-blank-lines=2, are set, then they have priority over any
4377 blank line deletion implied by the -kgb flags of this section, so
4378 no blank lines will be deleted.
4379
4380 For another example, if a keyword group ends at a sub and the flag
4381 kgba=0 requests no blank line there, but we also have
4382 --blank-lines-before-subs=2, then two blank lines will still be
4383 introduced before the sub.
4384
4385 • The introduction of blank lines does not occur if it would conflict
4386 with other input controls or code validity. For example, a blank
4387 line will not be placed within a here-doc or within a section of
4388 code marked with format skipping comments. And in general, a blank
4389 line will only be introduced at the end of a group if the next
4390 statement is a line of code.
4391
4392 • The count which is used to determine the group size is not the
4393 number of lines but rather the total number of keywords which are
4394 found. Individual statements with a certain leading keyword may
4395 continue on multiple lines, but if any of these lines is nested
4396 more than one level deep then that group will be ended.
4397
4398 • The search for groups of lines with similar leading keywords is
4399 based on the input source, not the final formatted source.
4400 Consequently, if the source code is badly formatted, it would be
4401 best to make a first formatting pass without these options.
4402
4403 Styles
4404 A style refers to a convenient collection of existing parameters.
4405
4406 -gnu, --gnu-style
4407 -gnu gives an approximation to the GNU Coding Standards (which do
4408 not apply to perl) as they are sometimes implemented. At present,
4409 this style overrides the default style with the following
4410 parameters:
4411
4412 -lp -bl -noll -pt=2 -bt=2 -sbt=2 -icp
4413
4414 To use this style with -xlp instead of -lp use -gnu -xlp.
4415
4416 -pbp, --perl-best-practices
4417 -pbp is an abbreviation for the parameters in the book Perl Best
4418 Practices by Damian Conway:
4419
4420 -l=78 -i=4 -ci=4 -st -se -vt=2 -cti=0 -pt=1 -bt=1 -sbt=1 -bbt=1 -nsfs -nolq
4421 -wbb="% + - * / x != == >= <= =~ !~ < > | & =
4422 **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x="
4423
4424 Please note that this parameter set includes -st and -se flags,
4425 which make perltidy act as a filter on one file only. These can be
4426 overridden by placing -nst and/or -nse after the -pbp parameter.
4427
4428 Also note that the value of continuation indentation, -ci=4, is
4429 equal to the value of the full indentation, -i=4. It is
4430 recommended that the either (1) the parameter -ci=2 be used
4431 instead, or (2) the flag -xci be set. This will help show
4432 structure, particularly when there are ternary statements. The
4433 following snippet illustrates these options.
4434
4435 # perltidy -pbp
4436 $self->{_text} = (
4437 !$section ? ''
4438 : $type eq 'item' ? "the $section entry"
4439 : "the section on $section"
4440 )
4441 . (
4442 $page
4443 ? ( $section ? ' in ' : '' ) . "the $page$page_ext manpage"
4444 : ' elsewhere in this document'
4445 );
4446
4447 # perltidy -pbp -ci=2
4448 $self->{_text} = (
4449 !$section ? ''
4450 : $type eq 'item' ? "the $section entry"
4451 : "the section on $section"
4452 )
4453 . (
4454 $page
4455 ? ( $section ? ' in ' : '' ) . "the $page$page_ext manpage"
4456 : ' elsewhere in this document'
4457 );
4458
4459 # perltidy -pbp -xci
4460 $self->{_text} = (
4461 !$section ? ''
4462 : $type eq 'item' ? "the $section entry"
4463 : "the section on $section"
4464 )
4465 . ( $page
4466 ? ( $section ? ' in ' : '' ) . "the $page$page_ext manpage"
4467 : ' elsewhere in this document'
4468 );
4469
4470 The -xci flag was developed after the -pbp parameters were
4471 published so you need to include it separately.
4472
4473 One-Line Blocks
4474 A one-line block is a block of code where the contents within the curly
4475 braces is short enough to fit on a single line. For example,
4476
4477 if ( -e $file ) { print "'$file' exists\n" }
4478
4479 The alternative, a block which spans multiple lines, is said to be a
4480 broken block. With few exceptions, perltidy retains existing one-line
4481 blocks, if it is possible within the line-length constraint, but it
4482 does not attempt to form new ones. In other words, perltidy will try
4483 to follow the input file regarding broken and unbroken blocks.
4484
4485 The main exception to this rule is that perltidy will attempt to form
4486 new one-line blocks following the keywords "map", "eval", and "sort",
4487 "eval", because these code blocks are often small and most clearly
4488 displayed in a single line. This behavior can be controlled with the
4489 flag --one-line-block-exclusion-list described below.
4490
4491 When the cuddled-else style is used, the default treatment of one-line
4492 blocks may interfere with the cuddled style. In this case, the default
4493 behavior may be changed with the flag --cuddled-break-option=n
4494 described elsehwere.
4495
4496 When an existing one-line block is longer than the maximum line length,
4497 and must therefore be broken into multiple lines, perltidy checks for
4498 and adds any optional terminating semicolon (unless the -nasc option is
4499 used) if the block is a code block.
4500
4501 -olbxl=s, --one-line-block-exclusion-list=s
4502 As noted above, perltidy will, by default, attempt to create new
4503 one-line blocks for certain block types. This flag allows the user
4504 to prevent this behavior for the block types listed in the string
4505 s. The list s may include any of the words "sort", "map", "grep",
4506 "eval", or it may be "*" to indicate all of these.
4507
4508 So for example to prevent multi-line eval blocks from becoming one-
4509 line blocks, the command would be -olbxl='eval'. In this case,
4510 existing one-line eval blocks will remain on one-line if possible,
4511 and existing multi-line eval blocks will remain multi-line blocks.
4512
4513 -olbn=n, --one-line-block-nesting=n
4514 Nested one-line blocks are lines with code blocks which themselves
4515 contain code blocks. For example, the following line is a nested
4516 one-line block.
4517
4518 foreach (@list) { if ($_ eq $asked_for) { last } ++$found }
4519
4520 The default behavior is to break such lines into multiple lines,
4521 but this behavior can be controlled with this flag. The values of
4522 n are:
4523
4524 n=0 break nested one-line blocks into multiple lines [DEFAULT]
4525 n=1 stable: keep existing nested-one line blocks intact
4526
4527 For the above example, the default formatting (-olbn=0) is
4528
4529 foreach (@list) {
4530 if ( $_ eq $asked_for ) { last }
4531 ++$found;
4532 }
4533
4534 If the parameter -olbn=1 is given, then the line will be left
4535 intact if it is a single line in the source, or it will be broken
4536 into multiple lines if it is broken in multiple lines in the
4537 source.
4538
4539 -olbs=n, --one-line-block-semicolons=n
4540 This flag controls the placement of semicolons at the end of one-
4541 line blocks. Semicolons are optional before a closing block brace,
4542 and frequently they are omitted at the end of a one-line block
4543 containing just a single statement. By default, perltidy follows
4544 the input file regarding these semicolons, but this behavior can be
4545 controlled by this flag. The values of n are:
4546
4547 n=0 remove terminal semicolons in one-line blocks having a single statement
4548 n=1 stable; keep input file placement of terminal semicolons [DEFAULT ]
4549 n=2 add terminal semicolons in all one-line blocks
4550
4551 Note that the n=2 option has no effect if adding semicolons is
4552 prohibited with the -nasc flag. Also not that while n=2 adds
4553 missing semicolons to all one-line blocks, regardless of
4554 complexity, the n=0 option only removes ending semicolons which
4555 terminate one-line blocks containing just one semicolon. So these
4556 two options are not exact inverses.
4557
4558 Forming new one-line blocks
4559 Sometimes it might be desirable to convert a script to have one-
4560 line blocks whenever possible. Although there is currently no flag
4561 for this, a simple workaround is to execute perltidy twice, once
4562 with the flag -noadd-newlines and then once again with normal
4563 parameters, like this:
4564
4565 cat infile | perltidy -nanl | perltidy >outfile
4566
4567 When executed on this snippet
4568
4569 if ( $? == -1 ) {
4570 die "failed to execute: $!\n";
4571 }
4572 if ( $? == -1 ) {
4573 print "Had enough.\n";
4574 die "failed to execute: $!\n";
4575 }
4576
4577 the result is
4578
4579 if ( $? == -1 ) { die "failed to execute: $!\n"; }
4580 if ( $? == -1 ) {
4581 print "Had enough.\n";
4582 die "failed to execute: $!\n";
4583 }
4584
4585 This shows that blocks with a single statement become one-line
4586 blocks.
4587
4588 Breaking existing one-line blocks
4589 There is no automatic way to break existing long one-line blocks
4590 into multiple lines, but this can be accomplished by processing a
4591 script, or section of a script, with a short value of the parameter
4592 maximum-line-length=n. Then, when the script is reformatted again
4593 with the normal parameters, the blocks which were broken will
4594 remain broken (with the exceptions noted above).
4595
4596 Another trick for doing this for certain block types is to format
4597 one time with the -cuddled-else flag and --cuddled-break-option=2.
4598 Then format again with the normal parameters. This will break any
4599 one-line blocks which are involved in a cuddled-else style.
4600
4601 Controlling Vertical Alignment
4602 Vertical alignment refers to lining up certain symbols in a list of
4603 consecutive similar lines to improve readability. For example, the
4604 "fat commas" are aligned in the following statement:
4605
4606 $data = $pkg->new(
4607 PeerAddr => join( ".", @port[ 0 .. 3 ] ),
4608 PeerPort => $port[4] * 256 + $port[5],
4609 Proto => 'tcp'
4610 );
4611
4612 Vertical alignment can be completely turned off using the -novalign
4613 flag mentioned below. However, vertical alignment can be forced to
4614 stop and restart by selectively introducing blank lines. For example,
4615 a blank has been inserted in the following code to keep somewhat
4616 similar things aligned.
4617
4618 %option_range = (
4619 'format' => [ 'tidy', 'html', 'user' ],
4620 'output-line-ending' => [ 'dos', 'win', 'mac', 'unix' ],
4621 'character-encoding' => [ 'none', 'utf8' ],
4622
4623 'block-brace-tightness' => [ 0, 2 ],
4624 'brace-tightness' => [ 0, 2 ],
4625 'paren-tightness' => [ 0, 2 ],
4626 'square-bracket-tightness' => [ 0, 2 ],
4627 );
4628
4629 Vertical alignment is implemented by locally increasing an existing
4630 blank space to produce alignment with an adjacent line. It cannot
4631 occur if there is no blank space to increase. So if a particular space
4632 is removed by one of the existing controls then vertical alignment
4633 cannot occur. Likewise, if a space is added with one of the controls,
4634 then vertical alignment might occur.
4635
4636 For example,
4637
4638 # perltidy -nwls='=>'
4639 $data = $pkg->new(
4640 PeerAddr=> join( ".", @port[ 0 .. 3 ] ),
4641 PeerPort=> $port[4] * 256 + $port[5],
4642 Proto=> 'tcp'
4643 );
4644
4645 Completely turning off vertical alignment with -novalign
4646 The default is to use vertical alignment, but vertical alignment
4647 can be completely turned of with the -novalign flag.
4648
4649 A lower level of control of vertical alignment is possible with
4650 three parameters -vc, -vsc, and -vbc. These independently control
4651 alignment of code, side comments and block comments. They are
4652 described in the next section.
4653
4654 The parameter -valign is in fact an alias for -vc -vsc -vbc, and
4655 its negative -novalign is an alias for -nvc -nvsc -nvbc.
4656
4657 Controlling code alignment with --valign-code or -vc
4658 The -vc flag enables alignment of code symbols such as =. The
4659 default is -vc. For detailed control of which symbols to align,
4660 see the -valign-exclude-list parameter below.
4661
4662 Controlling side comment alignment with --valign-side-comments or -vsc
4663 The -vsc flag enables alignment of side comments and is enabled by
4664 default. If side comment alignment is disabled with -nvsc they
4665 will appear at a fixed space from the preceding code token. The
4666 default is -vsc
4667
4668 Controlling block comment alignment with --valign-block-comments or
4669 -vbc
4670 When -vbc is enabled, block comments can become aligned for example
4671 if one comment of a consecutive sequence of comments becomes
4672 outdented due a length in excess of the maximum line length. If
4673 this occurs, the entire group of comments will remain aligned and
4674 be outdented by the same amount. This coordinated alignment will
4675 not occur if -nvbc is set. The default is -vbc.
4676
4677 Finer alignment control with --valign-exclusion-list=s or -vxl=s and
4678 --valign-inclusion-list=s or -vil=s
4679 More detailed control of alignment types is available with these
4680 two parameters. Most of the vertical alignments in typical
4681 programs occur at one of the tokens ',', '=', and '=>', but many
4682 other alignments are possible and are given in the following list:
4683
4684 = **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x=
4685 { ( ? : , ; => && || ~~ !~~ =~ !~ // <=> -> q
4686 if unless and or err for foreach while until
4687
4688 These alignment types correspond to perl symbols, operators and
4689 keywords except for 'q', which refers to the special case of
4690 alignment in a 'use' statement of qw quotes and empty parens.
4691
4692 They are all enabled by default, but they can be selectively
4693 disabled by including one or more of these tokens in the space-
4694 separated list valign-exclusion-list=s. For example, the following
4695 would prevent alignment at = and if:
4696
4697 --valign-exclusion-list='= if'
4698
4699 If it is simpler to specify only the token types which are to be
4700 aligned, then include the types which are to be aligned in the list
4701 of --valign-inclusion-list. In that case you may leave the valign-
4702 exclusion-list undefined, or use the special symbol * for the
4703 exclusion list. For example, the following parameters enable
4704 alignment only at commas and 'fat commas':
4705
4706 --valign-inclusion-list=', =>'
4707 --valign-exclusion-list='*' ( this is optional and may be omitted )
4708
4709 These parameter lists should consist of space-separated tokens from
4710 the above list of possible alignment tokens, or a '*'. If an
4711 unrecognized token appears, it is simply ignored. And if a specific
4712 token is entered in both lists by mistake then the exclusion list
4713 has priority.
4714
4715 The default values of these parameters enable all alignments and
4716 are equivalent to
4717
4718 --valign-exclusion-list=' '
4719 --valign-inclusion-list='*'
4720
4721 To illustrate, consider the following snippet with default
4722 formatting
4723
4724 # perltidy
4725 $co_description = ($color) ? 'bold cyan' : ''; # description
4726 $co_prompt = ($color) ? 'bold green' : ''; # prompt
4727 $co_unused = ($color) ? 'on_green' : 'reverse'; # unused
4728
4729 To exclude all alignments except the equals (i.e., include only
4730 equals) we could use:
4731
4732 # perltidy -vil='='
4733 $co_description = ($color) ? 'bold cyan' : ''; # description
4734 $co_prompt = ($color) ? 'bold green' : ''; # prompt
4735 $co_unused = ($color) ? 'on_green' : 'reverse'; # unused
4736
4737 To exclude only the equals we could use:
4738
4739 # perltidy -vxl='='
4740 $co_description = ($color) ? 'bold cyan' : ''; # description
4741 $co_prompt = ($color) ? 'bold green' : ''; # prompt
4742 $co_unused = ($color) ? 'on_green' : 'reverse'; # unused
4743
4744 Notice in this last example that although only the equals alignment
4745 was excluded, the ternary alignments were also lost. This happens
4746 because the vertical aligner sweeps from left-to-right and usually
4747 stops if an important alignment cannot be made for some reason.
4748
4749 But also notice that side comments remain aligned because their
4750 alignment is controlled separately with the parameter
4751 --valign-side_comments described above.
4752
4753 Aligning postfix unless and if with --valign-if-unless or -viu
4754 By default, postfix if terms align and postfix unless terms align,
4755 but separately. For example,
4756
4757 # perltidy [DEFAULT]
4758 print "Tried to add: @ResolveRPM\n" if ( @ResolveRPM and !$Quiet );
4759 print "Would need: @DepList\n" if ( @DepList and !$Quiet );
4760 print "RPM Output:\n" unless $Quiet;
4761 print join( "\n", @RPMOutput ) . "\n" unless $Quiet;
4762
4763 The -viu flag causes a postfix unless to be treated as if it were a
4764 postfix if for purposes of alignment. Thus
4765
4766 # perltidy -viu
4767 print "Tried to add: @ResolveRPM\n" if ( @ResolveRPM and !$Quiet );
4768 print "Would need: @DepList\n" if ( @DepList and !$Quiet );
4769 print "RPM Output:\n" unless $Quiet;
4770 print join( "\n", @RPMOutput ) . "\n" unless $Quiet;
4771
4772 Extended Syntax
4773 This section describes some parameters for dealing with extended
4774 syntax.
4775
4776 For another method of handling extended syntax see the section
4777 "Skipping Selected Sections of Code".
4778
4779 Also note that the module Perl::Tidy supplies a pre-filter and post-
4780 filter capability. This requires calling the module from a separate
4781 program rather than through the binary perltidy.
4782
4783 -xs, --extended-syntax
4784 This flag allows perltidy to handle certain common extensions to
4785 the standard syntax without complaint.
4786
4787 For example, without this flag a structure such as the following
4788 would generate a syntax error:
4789
4790 Method deposit( Num $amount) {
4791 $self->balance( $self->balance + $amount );
4792 }
4793
4794 This flag is enabled by default but it can be deactivated with
4795 -nxs. Probably the only reason to deactivate this flag is to
4796 generate more diagnostic messages when debugging a script.
4797
4798 -sal=s, --sub-alias-list=s
4799 This flag causes one or more words to be treated the same as if
4800 they were the keyword sub. The string s contains one or more alias
4801 words, separated by spaces or commas.
4802
4803 For example,
4804
4805 perltidy -sal='method fun _sub M4'
4806
4807 will cause the perltidy to treat the words 'method', 'fun', '_sub'
4808 and 'M4' the same as if they were 'sub'. Note that if the alias
4809 words are separated by spaces then the string of words should be
4810 placed in quotes.
4811
4812 Note that several other parameters accept a list of keywords,
4813 including 'sub' (see "Specifying Block Types"). You do not need to
4814 include any sub aliases in these lists. Just include keyword 'sub'
4815 if you wish, and all aliases are automatically included.
4816
4817 -gal=s, --grep-alias-list=s
4818 This flag allows a code block following an external 'list operator'
4819 function to be formatted as if it followed one of the built-in
4820 keywords grep, map or sort. The string s contains the names of
4821 one or more such list operators, separated by spaces or commas.
4822
4823 By 'list operator' is meant a function which is invoked in the form
4824
4825 word {BLOCK} @list
4826
4827 Perltidy tries to keep code blocks for these functions intact,
4828 since they are usually short, and does not automatically break
4829 after the closing brace since a list may follow. It also does some
4830 special handling of continuation indentation.
4831
4832 For example, the code block arguments to functions 'My_grep' and
4833 'My_map' can be given formatting like 'grep' with
4834
4835 perltidy -gal='My_grep My_map'
4836
4837 By default, the following list operators in List::Util are
4838 automatically included:
4839
4840 all any first none notall reduce reductions
4841
4842 Any operators specified with --grep-alias-list are added to this
4843 list. The next parameter can be used to remove words from this
4844 default list.
4845
4846 -gaxl=s, --grep-alias-exclusion-list=s
4847 The -gaxl=s flag provides a method for removing any of the default
4848 list operators given above by listing them in the string s. To
4849 remove all of the default operators use -gaxl='*'.
4850
4851 -uf=s, --use-feature=s
4852 This flag tells perltidy to allow or disallow the syntax associated
4853 a pragma in string s. The current possible settings are:
4854
4855 • --use-feature='class'. This tells perltidy to recognized the
4856 special words class, method, field, and ADJUST as defined for
4857 this feature.
4858
4859 • --use-feature='noclass'. This tells perltidy not to treat
4860 words class, method, field, ADJUST specially.
4861
4862 • Neither of these (--use-feature not defined). This is the
4863 DEFAULT and recommended setting. In this case perltidy will try
4864 to automatically handle both the newer --use-feature 'class'
4865 syntax as well as some conflicting uses of some of these
4866 special words by exisiting modules.
4867
4868 Note that this parameter is independent of any use feature control
4869 lines within a script. Perltidy does not look for or read such
4870 control lines. This is because perltidy must be able to work on
4871 small chunks of code sent from an editor, so it cannot assume that
4872 such lines will be within the lines being formatted.
4873
4874 Other Controls
4875 Deleting selected text
4876 Perltidy can selectively delete comments and/or pod documentation.
4877 The command -dac or --delete-all-comments will delete all comments
4878 and all pod documentation, leaving just code and any leading system
4879 control lines.
4880
4881 The command -dp or --delete-pod will remove all pod documentation
4882 (but not comments).
4883
4884 Two commands which remove comments (but not pod) are: -dbc or
4885 --delete-block-comments and -dsc or --delete-side-comments.
4886 (Hanging side comments will be deleted with side comments here.)
4887
4888 When side comments are deleted, any special control side comments
4889 for non-indenting braces will be retained unless they are
4890 deactivated with a -nnib flag.
4891
4892 The negatives of these commands also work, and are the defaults.
4893 When block comments are deleted, any leading 'hash-bang' will be
4894 retained. Also, if the -x flag is used, any system commands before
4895 a leading hash-bang will be retained (even if they are in the form
4896 of comments).
4897
4898 Writing selected text to a file
4899 When perltidy writes a formatted text file, it has the ability to
4900 also send selected text to a file with a .TEE extension. This text
4901 can include comments and pod documentation.
4902
4903 The command -tac or --tee-all-comments will write all comments and
4904 all pod documentation.
4905
4906 The command -tp or --tee-pod will write all pod documentation (but
4907 not comments).
4908
4909 The commands which write comments (but not pod) are: -tbc or
4910 --tee-block-comments and -tsc or --tee-side-comments. (Hanging
4911 side comments will be written with side comments here.)
4912
4913 The negatives of these commands also work, and are the defaults.
4914
4915 Using a .perltidyrc command file
4916 If you use perltidy frequently, you probably won't be happy until
4917 you create a .perltidyrc file to avoid typing commonly-used
4918 parameters. Perltidy will first look in your current directory for
4919 a command file named .perltidyrc. If it does not find one, it will
4920 continue looking for one in other standard locations.
4921
4922 These other locations are system-dependent, and may be displayed
4923 with the command "perltidy -dpro". Under Unix systems, it will
4924 first look for an environment variable PERLTIDY. Then it will look
4925 for a .perltidyrc file in the home directory, and then for a
4926 system-wide file /usr/local/etc/perltidyrc, and then it will look
4927 for /etc/perltidyrc. Note that these last two system-wide files do
4928 not have a leading dot. Further system-dependent information will
4929 be found in the INSTALL file distributed with perltidy.
4930
4931 Under Windows, perltidy will also search for a configuration file
4932 named perltidy.ini since Windows does not allow files with a
4933 leading period (.). Use "perltidy -dpro" to see the possible
4934 locations for your system. An example might be C:\Documents and
4935 Settings\All Users\perltidy.ini.
4936
4937 Another option is the use of the PERLTIDY environment variable.
4938 The method for setting environment variables depends upon the
4939 version of Windows that you are using.
4940
4941 Under Windows NT / 2000 / XP the PERLTIDY environment variable can
4942 be placed in either the user section or the system section. The
4943 later makes the configuration file common to all users on the
4944 machine. Be sure to enter the full path of the configuration file
4945 in the value of the environment variable. Ex.
4946 PERLTIDY=C:\Documents and Settings\perltidy.ini
4947
4948 The configuration file is free format, and simply a list of
4949 parameters, just as they would be entered on a command line. Any
4950 number of lines may be used, with any number of parameters per
4951 line, although it may be easiest to read with one parameter per
4952 line. Comment text begins with a #, and there must also be a space
4953 before the # for side comments. It is a good idea to put complex
4954 parameters in either single or double quotes.
4955
4956 Here is an example of a .perltidyrc file:
4957
4958 # This is a simple of a .perltidyrc configuration file
4959 # This implements a highly spaced style
4960 -se # errors to standard error output
4961 -w # show all warnings
4962 -bl # braces on new lines
4963 -pt=0 # parens not tight at all
4964 -bt=0 # braces not tight
4965 -sbt=0 # square brackets not tight
4966
4967 The parameters in the .perltidyrc file are installed first, so any
4968 parameters given on the command line will have priority over them.
4969
4970 To avoid confusion, perltidy ignores any command in the .perltidyrc
4971 file which would cause some kind of dump and an exit. These are:
4972
4973 -h -v -ddf -dln -dop -dsn -dtt -dwls -dwrs -ss
4974
4975 There are several options may be helpful in debugging a .perltidyrc
4976 file:
4977
4978 • A very helpful command is --dump-profile or -dpro. It writes a
4979 list of all configuration filenames tested to standard output,
4980 and if a file is found, it dumps the content to standard output
4981 before exiting. So, to find out where perltidy looks for its
4982 configuration files, and which one if any it selects, just
4983 enter
4984
4985 perltidy -dpro
4986
4987 • It may be simplest to develop and test configuration files with
4988 alternative names, and invoke them with -pro=filename on the
4989 command line. Then rename the desired file to .perltidyrc when
4990 finished.
4991
4992 • The parameters in the .perltidyrc file can be switched off with
4993 the -npro option.
4994
4995 • The commands --dump-options, --dump-defaults,
4996 --dump-long-names, and --dump-short-names, all described below,
4997 may all be helpful.
4998
4999 Creating a new abbreviation
5000 A special notation is available for use in a .perltidyrc file for
5001 creating an abbreviation for a group of options. This can be used
5002 to create a shorthand for one or more styles which are frequently,
5003 but not always, used. The notation is to group the options within
5004 curly braces which are preceded by the name of the alias (without
5005 leading dashes), like this:
5006
5007 newword {
5008 -opt1
5009 -opt2
5010 }
5011
5012 where newword is the abbreviation, and opt1, etc, are existing
5013 parameters or other abbreviations. The main syntax requirement is
5014 that the new abbreviation along with its opening curly brace must
5015 begin on a new line. Space before and after the curly braces is
5016 optional.
5017
5018 For a specific example, the following line
5019
5020 oneliner { --maximum-line-length=0 --noadd-newlines --noadd-terminal-newline}
5021
5022 or equivalently with abbreviations
5023
5024 oneliner { -l=0 -nanl -natnl }
5025
5026 could be placed in a .perltidyrc file to temporarily override the
5027 maximum line length with a large value, to temporarily prevent new
5028 line breaks from being added, and to prevent an extra newline
5029 character from being added the file. All other settings in the
5030 .perltidyrc file still apply. Thus it provides a way to format a
5031 long 'one liner' when perltidy is invoked with
5032
5033 perltidy --oneliner ...
5034
5035 (Either "-oneliner" or "--oneliner" may be used).
5036
5037 Skipping leading non-perl commands with -x or --look-for-hash-bang
5038 If your script has leading lines of system commands or other text
5039 which are not valid perl code, and which are separated from the
5040 start of the perl code by a "hash-bang" line, ( a line of the form
5041 "#!...perl" ), you must use the -x flag to tell perltidy not to
5042 parse and format any lines before the "hash-bang" line. This
5043 option also invokes perl with a -x flag when checking the syntax.
5044 This option was originally added to allow perltidy to parse
5045 interactive VMS scripts, but it should be used for any script which
5046 is normally invoked with "perl -x".
5047
5048 Please note: do not use this flag unless you are sure your script
5049 needs it. Parsing errors can occur if it does not have a hash-
5050 bang, or, for example, if the actual first hash-bang is in a here-
5051 doc. In that case a parsing error will occur because the
5052 tokenization will begin in the middle of the here-doc.
5053
5054 Making a file unreadable
5055 The goal of perltidy is to improve the readability of files, but
5056 there are two commands which have the opposite effect, --mangle and
5057 --extrude. They are actually merely aliases for combinations of
5058 other parameters. Both of these strip all possible whitespace, but
5059 leave comments and pod documents, so that they are essentially
5060 reversible. The difference between these is that --mangle puts the
5061 fewest possible line breaks in a script while --extrude puts the
5062 maximum possible. Note that these options do not provided any
5063 meaningful obfuscation, because perltidy can be used to reformat
5064 the files. They were originally developed to help test the
5065 tokenization logic of perltidy, but they have other uses. One use
5066 for --mangle is the following:
5067
5068 perltidy --mangle myfile.pl -st | perltidy -o myfile.pl.new
5069
5070 This will form the maximum possible number of one-line blocks (see
5071 next section), and can sometimes help clean up a badly formatted
5072 script.
5073
5074 A similar technique can be used with --extrude instead of --mangle
5075 to make the minimum number of one-line blocks.
5076
5077 Another use for --mangle is to combine it with -dac to reduce the
5078 file size of a perl script.
5079
5080 Debugging
5081 The following flags are available for debugging:
5082
5083 --dump-cuddled-block-list or -dcbl will dump to standard output the
5084 internal hash of cuddled block types created by a
5085 -cuddled-block-list input string.
5086
5087 --dump-defaults or -ddf will write the default option set to
5088 standard output and quit
5089
5090 --dump-profile or -dpro will write the name of the current
5091 configuration file and its contents to standard output and quit.
5092
5093 --dump-options or -dop will write current option set to standard
5094 output and quit.
5095
5096 --dump-long-names or -dln will write all command line long names
5097 (passed to Get_options) to standard output and quit.
5098
5099 --dump-short-names or -dsn will write all command line short names
5100 to standard output and quit.
5101
5102 --dump-token-types or -dtt will write a list of all token types to
5103 standard output and quit.
5104
5105 --dump-want-left-space or -dwls will write the hash
5106 %want_left_space to standard output and quit. See the section on
5107 controlling whitespace around tokens.
5108
5109 --dump-want-right-space or -dwrs will write the hash
5110 %want_right_space to standard output and quit. See the section on
5111 controlling whitespace around tokens.
5112
5113 --no-memoize or -nmem will turn of memoizing. Memoization can
5114 reduce run time when running perltidy repeatedly in a single
5115 process. It is on by default but can be deactivated for testing
5116 with -nmem.
5117
5118 --no-timestamp or -nts will eliminate any time stamps in output
5119 files to prevent differences in dates from causing test
5120 installation scripts to fail. There are just a couple of places
5121 where timestamps normally occur. One is in the headers of html
5122 files, and another is when the -cscw option is selected. The
5123 default is to allow timestamps (--timestamp or -ts).
5124
5125 --file-size-order or -fso will cause files to be processed in order
5126 of increasing size, when multiple files are being processed. This
5127 is useful during program development, when large numbers of files
5128 with varying sizes are processed, because it can reduce virtual
5129 memory usage.
5130
5131 --maximum-file-size-mb=n or -maxfs=n specifies the maximum file
5132 size in megabytes that perltidy will attempt to format. This
5133 parameter is provided to avoid causing system problems by
5134 accidentally attempting to format an extremely large data file.
5135 Most perl scripts are less than about 2 MB in size. The integer n
5136 has a default value of 10, so perltidy will skip formatting files
5137 which have a size greater than 10 MB. The command to increase the
5138 limit to 20 MB for example would be
5139
5140 perltidy -maxfs=20
5141
5142 This only applies to files specified by filename on the command
5143 line.
5144
5145 --maximum-level-errors=n or -maxle=n specifies the maximum number
5146 of indentation level errors are allowed before perltidy skips
5147 formatting and just outputs a file verbatim. The default is n=1.
5148 This means that if the final indentation of a script differs from
5149 the starting indentation by more than 1 levels, the file will be
5150 output verbatim. To avoid formatting if there are any indentation
5151 level errors use -maxle=0. To skip this check you can either set n
5152 equal to a large number, such as n=100, or set n=-1.
5153
5154 For example, the following script has level error of 3 and will be
5155 output verbatim
5156
5157 Input and default output:
5158 {{{
5159
5160
5161 perltidy -maxle=100
5162 {
5163 {
5164 {
5165
5166 --maximum-unexpected-errors=n or -maxue=n specifies the maximum
5167 number of unexpected tokenization errors are allowed before
5168 formatting is skipped and a script is output verbatim. The
5169 intention is to avoid accidentally formatting a non-perl script,
5170 such as an html file for example. This check can be turned off by
5171 setting n=0.
5172
5173 A recommended value is n=3. However, the default is n=0 (skip this
5174 check) to avoid causing problems with scripts which have extended
5175 syntaxes.
5176
5177 -DEBUG will write a file with extension .DEBUG for each input file
5178 showing the tokenization of all lines of code.
5179
5180 Making a table of information on code blocks
5181 A table listing information about the blocks of code in a file can
5182 be made with --dump-block-summary, or -dbs. This causes perltidy
5183 to read and parse the file, write a table of comma-separated values
5184 for selected code blocks to the standard output, and then exit.
5185 This parameter must be on the command line, not in a .perlticyrc
5186 file, and it requires a single file name on the command line. For
5187 example
5188
5189 perltidy -dbs somefile.pl >blocks.csv
5190
5191 produces an output file blocks.csv whose lines hold these
5192 parameters:
5193
5194 filename - the name of the file
5195 line - the line number of the opening brace of this block
5196 line_count - the number of lines between opening and closing braces
5197 code_lines - the number of lines excluding blanks, comments, and pod
5198 type - the block type (sub, for, foreach, ...)
5199 name - the block name if applicable (sub name, label, asub name)
5200 depth - the nesting depth of the opening block brace
5201 max_change - the change in depth to the most deeply nested code block
5202 block_count - the total number of code blocks nested in this block
5203 mccabe_count - the McCabe complexity measure of this code block
5204
5205 This feature was developed to help identify complex sections of
5206 code as an aid in refactoring. The McCabe complexity measure
5207 follows the definition used by Perl::Critic. By default the table
5208 contains these values for subroutines, but the user may request
5209 them for any or all blocks of code or packages. For blocks which
5210 are loops nested within loops, a postfix '+' to the "type" is added
5211 to indicate possible code complexity. Although the table does not
5212 otherwise indicate which blocks are nested in other blocks, this
5213 can be determined by computing and comparing the block ending line
5214 numbers.
5215
5216 By default the table lists subroutines with more than 20
5217 "code_lines", but this can be changed with the following two
5218 parameters:
5219
5220 --dump-block-minimum-lines=n, or -dbl=n, where n is the minimum
5221 number of "code_lines" to be included. The default is -n=20. Note
5222 that "code_lines" is the number of lines excluding and comments,
5223 blanks and pod.
5224
5225 --dump-block-types=s, or -dbt=s, where string s is a list of block
5226 types to be included. The type of a block is either the name of
5227 the perl builtin keyword for that block (such as sub if elsif else
5228 for foreach ..) or the word immediately before the opening brace.
5229 In addition, there are a few symbols for special block types, as
5230 follows:
5231
5232 if elsif else for foreach ... any keyword introducing a block
5233 sub - any sub or anynomous sub
5234 asub - any anonymous sub
5235 * - any block except nameless blocks
5236 + - any nested inner block loop
5237 package - any package or class
5238 closure - any nameless block
5239
5240 In addition, specific block loop types which are nested in other
5241 loops can be selected by adding a + after the block name. (Nested
5242 loops are sometimes good candidates for restructuring).
5243
5244 The default is -dbt='sub'.
5245
5246 In the following examples a table "block.csv" is created for a file
5247 "somefile.pl":
5248
5249 • This selects both "subs" and "packages" which have 20 or more
5250 lines of code. This can be useful in code which contains
5251 multiple packages.
5252
5253 perltidy -dbs -dbt='sub package' somefile.pl >blocks.csv
5254
5255 • This selects block types "sub for foreach while" with 10 or
5256 more code lines.
5257
5258 perltidy -dbs -dbl=10 -dbt='sub for foreach while' somefile.pl >blocks.csv
5259
5260 • This selects blocks with 2 or more code lines which are type
5261 "sub" or which are inner loops.
5262
5263 perltidy -dbs -dbl=2 -dbt='sub +' somefile.pl >blocks.csv
5264
5265 • This selects every block and package.
5266
5267 perltidy -dbs -dbl=1 -dbt='* closure' somefile.pl >blocks.csv
5268
5269 Working with MakeMaker, AutoLoader and SelfLoader
5270 The first $VERSION line of a file which might be eval'd by
5271 MakeMaker is passed through unchanged except for indentation. Use
5272 --nopass-version-line, or -npvl, to deactivate this feature.
5273
5274 If the AutoLoader module is used, perltidy will continue formatting
5275 code after seeing an __END__ line. Use --nolook-for-autoloader, or
5276 -nlal, to deactivate this feature.
5277
5278 Likewise, if the SelfLoader module is used, perltidy will continue
5279 formatting code after seeing a __DATA__ line. Use
5280 --nolook-for-selfloader, or -nlsl, to deactivate this feature.
5281
5282 Working around problems with older version of Perl
5283 Perltidy contains a number of rules which help avoid known
5284 subtleties and problems with older versions of perl, and these
5285 rules always take priority over whatever formatting flags have been
5286 set. For example, perltidy will usually avoid starting a new line
5287 with a bareword, because this might cause problems if "use strict"
5288 is active.
5289
5290 There is no way to override these rules.
5291
5293 The -html master switch
5294 The flag -html causes perltidy to write an html file with extension
5295 .html. So, for example, the following command
5296
5297 perltidy -html somefile.pl
5298
5299 will produce a syntax-colored html file named somefile.pl.html
5300 which may be viewed with a browser.
5301
5302 Please Note: In this case, perltidy does not do any formatting to
5303 the input file, and it does not write a formatted file with
5304 extension .tdy. This means that two perltidy runs are required to
5305 create a fully reformatted, html copy of a script.
5306
5307 The -pre flag for code snippets
5308 When the -pre flag is given, only the pre-formatted section, within
5309 the <PRE> and </PRE> tags, will be output. This simplifies
5310 inclusion of the output in other files. The default is to output a
5311 complete web page.
5312
5313 The -nnn flag for line numbering
5314 When the -nnn flag is given, the output lines will be numbered.
5315
5316 The -toc, or --html-table-of-contents flag
5317 By default, a table of contents to packages and subroutines will be
5318 written at the start of html output. Use -ntoc to prevent this.
5319 This might be useful, for example, for a pod document which
5320 contains a number of unrelated code snippets. This flag only
5321 influences the code table of contents; it has no effect on any
5322 table of contents produced by pod2html (see next item).
5323
5324 The -pod, or --pod2html flag
5325 There are two options for formatting pod documentation. The
5326 default is to pass the pod through the Pod::Html module (which
5327 forms the basis of the pod2html utility). Any code sections are
5328 formatted by perltidy, and the results then merged. Note: perltidy
5329 creates a temporary file when Pod::Html is used; see "FILES".
5330 Also, Pod::Html creates temporary files for its cache.
5331
5332 NOTE: Perltidy counts the number of "=cut" lines, and either moves
5333 the pod text to the top of the html file if there is one "=cut", or
5334 leaves the pod text in its original order (interleaved with code)
5335 otherwise.
5336
5337 Most of the flags accepted by pod2html may be included in the
5338 perltidy command line, and they will be passed to pod2html. In
5339 some cases, the flags have a prefix "pod" to emphasize that they
5340 are for the pod2html, and this prefix will be removed before they
5341 are passed to pod2html. The flags which have the additional "pod"
5342 prefix are:
5343
5344 --[no]podheader --[no]podindex --[no]podrecurse --[no]podquiet
5345 --[no]podverbose --podflush
5346
5347 The flags which are unchanged from their use in pod2html are:
5348
5349 --backlink=s --cachedir=s --htmlroot=s --libpods=s --title=s
5350 --podpath=s --podroot=s
5351
5352 where 's' is an appropriate character string. Not all of these
5353 flags are available in older versions of Pod::Html. See your
5354 Pod::Html documentation for more information.
5355
5356 The alternative, indicated with -npod, is not to use Pod::Html, but
5357 rather to format pod text in italics (or whatever the stylesheet
5358 indicates), without special html markup. This is useful, for
5359 example, if pod is being used as an alternative way to write
5360 comments.
5361
5362 The -frm, or --frames flag
5363 By default, a single html output file is produced. This can be
5364 changed with the -frm option, which creates a frame holding a table
5365 of contents in the left panel and the source code in the right
5366 side. This simplifies code browsing. Assume, for example, that the
5367 input file is MyModule.pm. Then, for default file extension
5368 choices, these three files will be created:
5369
5370 MyModule.pm.html - the frame
5371 MyModule.pm.toc.html - the table of contents
5372 MyModule.pm.src.html - the formatted source code
5373
5374 Obviously this file naming scheme requires that output be directed
5375 to a real file (as opposed to, say, standard output). If this is
5376 not the case, or if the file extension is unknown, the -frm option
5377 will be ignored.
5378
5379 The -text=s, or --html-toc-extension flag
5380 Use this flag to specify the extra file extension of the table of
5381 contents file when html frames are used. The default is "toc".
5382 See "Specifying File Extensions".
5383
5384 The -sext=s, or --html-src-extension flag
5385 Use this flag to specify the extra file extension of the content
5386 file when html frames are used. The default is "src". See
5387 "Specifying File Extensions".
5388
5389 The -hent, or --html-entities flag
5390 This flag controls the use of Html::Entities for html formatting.
5391 By default, the module Html::Entities is used to encode special
5392 symbols. This may not be the right thing for some browser/language
5393 combinations. Use --nohtml-entities or -nhent to prevent this.
5394
5395 Style Sheets
5396 Style sheets make it very convenient to control and adjust the
5397 appearance of html pages. The default behavior is to write a page
5398 of html with an embedded style sheet.
5399
5400 An alternative to an embedded style sheet is to create a page with
5401 a link to an external style sheet. This is indicated with the
5402 -css=filename, where the external style sheet is filename. The
5403 external style sheet filename will be created if and only if it
5404 does not exist. This option is useful for controlling multiple
5405 pages from a single style sheet.
5406
5407 To cause perltidy to write a style sheet to standard output and
5408 exit, use the -ss, or --stylesheet, flag. This is useful if the
5409 style sheet could not be written for some reason, such as if the
5410 -pre flag was used. Thus, for example,
5411
5412 perltidy -html -ss >mystyle.css
5413
5414 will write a style sheet with the default properties to file
5415 mystyle.css.
5416
5417 The use of style sheets is encouraged, but a web page without a
5418 style sheets can be created with the flag -nss. Use this option if
5419 you must to be sure that older browsers (roughly speaking, versions
5420 prior to 4.0 of Netscape Navigator and Internet Explorer) can
5421 display the syntax-coloring of the html files.
5422
5423 Controlling HTML properties
5424 Note: It is usually more convenient to accept the default
5425 properties and then edit the stylesheet which is produced.
5426 However, this section shows how to control the properties with
5427 flags to perltidy.
5428
5429 Syntax colors may be changed from their default values by flags of
5430 the either the long form, -html-color-xxxxxx=n, or more
5431 conveniently the short form, -hcx=n, where xxxxxx is one of the
5432 following words, and x is the corresponding abbreviation:
5433
5434 Token Type xxxxxx x
5435 ---------- -------- --
5436 comment comment c
5437 number numeric n
5438 identifier identifier i
5439 bareword, function bareword w
5440 keyword keyword k
5441 quite, pattern quote q
5442 here doc text here-doc-text h
5443 here doc target here-doc-target hh
5444 punctuation punctuation pu
5445 parentheses paren p
5446 structural braces structure s
5447 semicolon semicolon sc
5448 colon colon co
5449 comma comma cm
5450 label label j
5451 sub definition name subroutine m
5452 pod text pod-text pd
5453
5454 A default set of colors has been defined, but they may be changed
5455 by providing values to any of the following parameters, where n is
5456 either a 6 digit hex RGB color value or an ascii name for a color,
5457 such as 'red'.
5458
5459 To illustrate, the following command will produce an html file
5460 somefile.pl.html with "aqua" keywords:
5461
5462 perltidy -html -hck=00ffff somefile.pl
5463
5464 and this should be equivalent for most browsers:
5465
5466 perltidy -html -hck=aqua somefile.pl
5467
5468 Perltidy merely writes any non-hex names that it sees in the html
5469 file. The following 16 color names are defined in the HTML 3.2
5470 standard:
5471
5472 black => 000000,
5473 silver => c0c0c0,
5474 gray => 808080,
5475 white => ffffff,
5476 maroon => 800000,
5477 red => ff0000,
5478 purple => 800080,
5479 fuchsia => ff00ff,
5480 green => 008000,
5481 lime => 00ff00,
5482 olive => 808000,
5483 yellow => ffff00
5484 navy => 000080,
5485 blue => 0000ff,
5486 teal => 008080,
5487 aqua => 00ffff,
5488
5489 Many more names are supported in specific browsers, but it is
5490 safest to use the hex codes for other colors. Helpful color tables
5491 can be located with an internet search for "HTML color tables".
5492
5493 Besides color, two other character attributes may be set: bold, and
5494 italics. To set a token type to use bold, use the flag
5495 --html-bold-xxxxxx or -hbx, where xxxxxx or x are the long or short
5496 names from the above table. Conversely, to set a token type to NOT
5497 use bold, use --nohtml-bold-xxxxxx or -nhbx.
5498
5499 Likewise, to set a token type to use an italic font, use the flag
5500 --html-italic-xxxxxx or -hix, where again xxxxxx or x are the long
5501 or short names from the above table. And to set a token type to
5502 NOT use italics, use --nohtml-italic-xxxxxx or -nhix.
5503
5504 For example, to use bold braces and lime color, non-bold, italics
5505 keywords the following command would be used:
5506
5507 perltidy -html -hbs -hck=00FF00 -nhbk -hik somefile.pl
5508
5509 The background color can be specified with
5510 --html-color-background=n, or -hcbg=n for short, where n is a 6
5511 character hex RGB value. The default color of text is the value
5512 given to punctuation, which is black as a default.
5513
5514 Here are some notes and hints:
5515
5516 1. If you find a preferred set of these parameters, you may want to
5517 create a .perltidyrc file containing them. See the perltidy man
5518 page for an explanation.
5519
5520 2. Rather than specifying values for these parameters, it is
5521 probably easier to accept the defaults and then edit a style sheet.
5522 The style sheet contains comments which should make this easy.
5523
5524 3. The syntax-colored html files can be very large, so it may be
5525 best to split large files into smaller pieces to improve download
5526 times.
5527
5529 Specifying Block Types
5530 Several parameters which refer to code block types may be customized by
5531 also specifying an associated list of block types. The type of a block
5532 is the name of the keyword which introduces that block, such as if,
5533 else, or sub. An exception is a labeled block, which has no keyword,
5534 and should be specified with just a colon. To specify all blocks use
5535 '*'.
5536
5537 The keyword sub indicates a named sub. For anonymous subs, use the
5538 special keyword asub.
5539
5540 For example, the following parameter specifies "sub", labels, "BEGIN",
5541 and "END" blocks:
5542
5543 -cscl="sub : BEGIN END"
5544
5545 (the meaning of the -cscl parameter is described above.) Note that
5546 quotes are required around the list of block types because of the
5547 spaces. For another example, the following list specifies all block
5548 types for vertical tightness:
5549
5550 -bbvtl='*'
5551
5552 Specifying File Extensions
5553 Several parameters allow default file extensions to be overridden. For
5554 example, a backup file extension may be specified with -bext=ext, where
5555 ext is some new extension. In order to provides the user some
5556 flexibility, the following convention is used in all cases to decide if
5557 a leading '.' should be used. If the extension "ext" begins with
5558 "A-Z", "a-z", or "0-9", then it will be appended to the filename with
5559 an intermediate '.' (or perhaps a '_' on VMS systems). Otherwise, it
5560 will be appended directly.
5561
5562 For example, suppose the file is somefile.pl. For "-bext=old", a '.'
5563 is added to give somefile.pl.old. For "-bext=.old", no additional '.'
5564 is added, so again the backup file is somefile.pl.old. For "-bext=~",
5565 then no dot is added, and the backup file will be somefile.pl~ .
5566
5568 The following list shows all short parameter names which allow a prefix
5569 'n' to produce the negated form:
5570
5571 D ame anl asbl asc ast asu atc atnl aws
5572 b baa baao bar bbao bbb bbc bbs bl bli
5573 boa boc bok bol bom bos bot cblx ce conv
5574 cpb cs csc cscb cscw dac dbc dbs dcbl dcsc
5575 ddf dln dnl dop dp dpro drc dsc dsm dsn
5576 dtc dtt dwic dwls dwrs dws eos f fpva frm
5577 fs fso gcs hbc hbcm hbco hbh hbhh hbi hbj
5578 hbk hbm hbn hbp hbpd hbpu hbq hbs hbsc hbv
5579 hbw hent hic hicm hico hih hihh hii hij hik
5580 him hin hip hipd hipu hiq his hisc hiv hiw
5581 hsc html ibc icb icp iob ipc isbc iscl kgb
5582 kgbd kgbi kis lal log lop lp lsl mem nib
5583 ohbr okw ola olc oll olq opr opt osbc osbr
5584 otr ple pod pvl q sac sbc sbl scbb schb
5585 scp scsb sct se sfp sfs skp sob sobb sohb
5586 sop sosb sot ssc st sts t tac tbc toc
5587 tp tqw trp ts tsc tso vbc vc viu vmll
5588 vsc w wfc wme wn x xbt xci xlp xs
5589
5590 Equivalently, the prefix 'no' or 'no-' on the corresponding long names
5591 may be used.
5592
5594 Parsing Limitations
5595 Perltidy should work properly on most perl scripts. It does a lot
5596 of self-checking, but still, it is possible that an error could be
5597 introduced and go undetected. Therefore, it is essential to make
5598 careful backups and to test reformatted scripts.
5599
5600 The main current limitation is that perltidy does not scan modules
5601 included with 'use' statements. This makes it necessary to guess
5602 the context of any bare words introduced by such modules. Perltidy
5603 has good guessing algorithms, but they are not infallible. When it
5604 must guess, it leaves a message in the log file.
5605
5606 If you encounter a bug, please report it.
5607
5608 What perltidy does not parse and format
5609 Perltidy indents but does not reformat comments and "qw" quotes.
5610 Perltidy does not in any way modify the contents of here documents
5611 or quoted text, even if they contain source code. (You could,
5612 however, reformat them separately). Perltidy does not format
5613 'format' sections in any way. And, of course, it does not modify
5614 pod documents.
5615
5617 Temporary files
5618 Under the -html option with the default --pod2html flag, a
5619 temporary file is required to pass text to Pod::Html. Unix systems
5620 will try to use the POSIX tmpnam() function. Otherwise the file
5621 perltidy.TMP will be temporarily created in the current working
5622 directory.
5623
5624 Special files when standard input is used
5625 When standard input is used, the log file, if saved, is
5626 perltidy.LOG, and any errors are written to perltidy.ERR unless the
5627 -se flag is set. These are saved in the current working directory.
5628
5629 Files overwritten
5630 The following file extensions are used by perltidy, and files with
5631 these extensions may be overwritten or deleted: .ERR, .LOG, .TEE,
5632 and/or .tdy, .html, and .bak, depending on the run type and
5633 settings.
5634
5635 Files extensions limitations
5636 Perltidy does not operate on files for which the run could produce
5637 a file with a duplicated file extension. These extensions include
5638 .LOG, .ERR, .TEE, and perhaps .tdy and .bak, depending on the run
5639 type. The purpose of this rule is to prevent generating confusing
5640 filenames such as somefile.tdy.tdy.tdy.
5641
5643 An exit value of 0, 1, or 2 is returned by perltidy to indicate the
5644 status of the result.
5645
5646 A exit value of 0 indicates that perltidy ran to completion with no
5647 error messages.
5648
5649 A non-zero exit value indicates some kind of problem was detected.
5650
5651 An exit value of 1 indicates that perltidy terminated prematurely,
5652 usually due to some kind of errors in the input parameters. This can
5653 happen for example if a parameter is misspelled or given an invalid
5654 value. Error messages in the standard error output will indicate the
5655 cause of any problem. If perltidy terminates prematurely then no
5656 output files will be produced.
5657
5658 An exit value of 2 indicates that perltidy was able to run to
5659 completion but there there are (1) warning messages in the standard
5660 error output related to parameter errors or problems and/or (2) warning
5661 messages in the perltidy error file(s) relating to possible syntax
5662 errors in one or more of the source script(s) being tidied. When
5663 multiple files are being processed, an error detected in any single
5664 file will produce this type of exit condition.
5665
5667 perlstyle(1), Perl::Tidy(3)
5668
5670 The perltidy binary uses the Perl::Tidy module and is installed when
5671 that module is installed. The module name is case-sensitive. For
5672 example, the basic command for installing with cpanm is 'cpanm
5673 Perl::Tidy'.
5674
5676 This man page documents perltidy version 20230912
5677
5679 The source code repository is at
5680 <https://github.com/perltidy/perltidy>.
5681
5682 To report a new bug or problem, use the "issues" link on this page.
5683
5685 Copyright (c) 2000-2023 by Steve Hancock
5686
5688 This package is free software; you can redistribute it and/or modify it
5689 under the terms of the "GNU General Public License".
5690
5691 Please refer to the file "COPYING" for details.
5692
5694 This package is distributed in the hope that it will be useful, but
5695 WITHOUT ANY WARRANTY; without even the implied warranty of
5696 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5697
5698 See the "GNU General Public License" for more details.
5699
5700
5701
5702perl v5.38.0 2023-09-13 PERLTIDY(1)