PERLTIDY(1p)

๐Ÿ“ฆ
this version ยท 6 versions
, in ubuntu resolute, ubuntu stonking

โœจ NAME โœจ

perltidy โ€” it's a perl script indenter and reformatter, and it's literally about to fix your whole messy file situation bestie ๐Ÿ’… (this is the PERLTIDY(1p) page, User Contributed Perl Documentation, in case you were wondering who made this gorgeousness)

๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

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

๐ŸŒธ DESCRIPTION ๐ŸŒธ

Okay so here's the vibe: Perltidy reads a perl script and writes an indented, reformatted script. That's the whole thing. The formatting process involves converting the script into a string of tokens, removing any non-essential whitespace, and then rewriting the string of tokens with whitespace using whatever rules are specified, or defaults. And this doesn't happen in one go โ€” it happens in a series of operations which can be controlled with the parameters described in this document. Slay. โœจ

Perltidy is a commandline frontend to the module Perl::Tidy. If you want documentation describing how to call the Perl::Tidy module from other applications, go see the separate documentation for Perl::Tidy. It's the file Perl::Tidy.pod in the source distribution. iykyk ๐Ÿซถ

Many users will find enough information in "EXAMPLES" to get started. New users may benefit from the short tutorial which can be found at http://perltidy.sourceforge.net/tutorial.html ๐ŸŽ€

A convenient aid to systematically defining a set of style parameters can be found at http://perltidy.sourceforge.net/stylekey.html ๐Ÿ’–

Perltidy can produce output on either of two modes, depending on the existence of an -html flag. Without this flag, the output is passed through a formatter. The default formatting tries to follow the recommendations in perlstyle(1), but it can be controlled in detail with numerous input parameters, which are described in "FORMATTING OPTIONS". ๐Ÿ‘‘

When the -html flag is given, the output is passed through an HTML formatter which is described in "HTML OPTIONS".


๐ŸŒˆ EXAMPLES ๐ŸŒˆ

Here are some example perltidy commands followed by their meanings โ€” come look at the menu bestie, everything looks good:

perltidy somefile.pl

This will produce a file somefile.pl.tdy containing the script reformatted using the default options, which approximate the style suggested in perlstyle(1). The source file somefile.pl is unchanged. (Your original is safe, she's untouched ๐Ÿ’…)

perltidy *.pl

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

perltidy -b file1.pl file2.pl

Modify file1.pl and file2.pl in place, and backup the originals to file1.pl.bak and file2.pl.bak. If file1.pl.bak and/or file2.pl.bak already exist, they will be overwritten. (yes, overwritten. no mercy. ๐Ÿ’€)

perltidy -b -bext='/' file1.pl file2.pl

Same as the previous example except that the backup files file1.pl.bak and file2.pl.bak will be deleted if there are no errors.

perltidy -gnu somefile.pl

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

perltidy -i=3 somefile.pl

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

perltidy -i=3 -et=8 somefile.pl

Same as the previous example, except that leading whitespace will be entabbed with one tab character per 8 spaces.

perltidy -ce -l=72 somefile.pl

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

perltidy -g somefile.pl

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

   perltidy -dbs -dbl=10 somefile.pl >blocks.csv

This will dump a table of comma-separated metrics for subroutines longer than 10 lines to blocks.csv.

    perltidy -duv somefile.pl >vars.txt

This will dump a list of unused and reused lexical variable names to vars.txt.

perltidy -html somefile.pl

This will produce a file somefile.pl.html containing the script with html markup. The output file will contain an embedded style sheet in the "<HEAD"> section which may be edited to change the appearance. ๐ŸŽ€

perltidy -html -css=mystyle.css somefile.pl

This will produce a file somefile.pl.html containing the script with html markup. This output file will contain a link to a separate style sheet file mystyle.css. If the file mystyle.css does not exist, it will be created. If it exists, it will not be overwritten.

perltidy -html -pre somefile.pl

Write an html snippet with only the "<PRE"> section to somefile.pl.html. This is useful when code snippets are being formatted for inclusion in a larger web page. No style sheet will be written in this case.

perltidy -html -ss >mystyle.css

Write a style sheet to mystyle.css and exit.

perltidy -html -frm mymodule.pm

Write html with a frame holding a table of contents and the source code. The output files will be mymodule.pm.html (the frame), mymodule.pm.toc.html (the table of contents), and mymodule.pm.src.html (the source code).


๐Ÿ’œ OPTIONS - OVERVIEW ๐Ÿ’œ

The entire command line is scanned for options, and they are processed before any files are processed. As a result, it does not matter whether flags are before or after any filenames. However, the relative order of parameters is important, with later parameters overriding the values of earlier parameters. So order matters bestie, don't come for me when the last one wins. โœจ

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

Most parameters which serve as on/off flags can be negated with a leading "n" (for the short name) or a leading "no" or "no-" (for the long name). For example, the flag to outdent long quotes is -olq or --outdent-long-quotes. The flag to skip this is -nolq or --nooutdent-long-quotes or --no-outdent-long-quotes.

Options may not be bundled together. In other words, options -q and -g may NOT be entered as -qg. (they're not a group chat, they don't travel together ๐Ÿ™ˆ)

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

๐Ÿงš I/O Control

The following parameters concern the files which are read and written.

  • -h, --help โ€” Show summary of usage and exit.
  • -v, --version โ€” Show perltidy VERSION number and exit.
  • -o=filename, --outfile=filename โ€” Name of the output file (only if a single input file is being processed). If no output file is specified, and output is not redirected to the standard output (see -st), the output will go to filename.tdy. [Note: - does not redirect to standard output. Use -st instead.] โš ๏ธ
  • -st, --standard-output โ€” Perltidy must be able to operate on an arbitrarily large number of files in a single run, with each output being directed to a different output file. Obviously this would conflict with outputting to the single standard output device, so a special flag, -st, is required to request outputting to the standard output. For example,
perltidy somefile.pl -st >somefile.new.pl

This option may only be used if there is just a single input file. The default is -nst or --nostandard-output.

  • -se, --standard-error-output โ€” If perltidy detects an error when processing file somefile.pl, its default behavior is to write error messages to file somefile.pl.ERR. Use -se to cause all error messages to be sent to the standard error output stream instead. This directive may be negated with -nse. Thus, you may place -se in a .perltidyrc and override it when desired with -nse on the command line.
  • -oext=ext, --output-file-extension=ext โ€” Change the extension of the output file to be ext instead of the default tdy (or html in case the --html option is used). See "Specifying File Extensions".
  • -opath=path, --output-path=path โ€” When perltidy creates a filename for an output file, by default it merely appends an extension to the path and basename of the input file. This parameter causes the path to be changed to path instead.

The path should end in a valid path separator character, but perltidy will try to add one if it is missing.

For example

 perltidy somefile.pl -opath=/tmp/

will produce /tmp/somefile.pl.tdy. Otherwise, somefile.pl.tdy will appear in whatever directory contains somefile.pl.

If the path contains spaces, it should be placed in quotes.

This parameter will be ignored if output is being directed to standard output, or if it is being specified explicitly with the --outfile=s parameter.

  • -b, --backup-and-modify-in-place โ€” Modify the input file or files in-place and save the original with the extension .bak. Any existing .bak file will be deleted. See next item for changing the default backup extension, and for eliminating the backup file altogether.
Please Note: Writing back to the input file increases the risk of data loss or corruption in the event of a software or hardware malfunction. Before using the -b parameter please be sure to have backups and verify that it works correctly in your environment and operating system. ๐Ÿ™ Like I'm so serious bestie, BACK UP FIRST.

A -b flag will be ignored if input is from standard input or goes to standard output, or if the -html flag is set.

In particular, if you want to use both the -b flag and the --perl-best-practices (-pbp) flag, then you must put a --nostandard-output (-nst) flag after the -pbp flag because it contains a --standard-output flag as one of its components, which means that output will go to the standard output stream. ๐Ÿ’€ sneaky.

  • -bext=ext, --backup-file-extension=ext โ€” This parameter serves two purposes: (1) to change the extension of the backup file to be something other than the default .bak, and (2) to indicate that no backup file should be saved.

To change the default extension to something other than .bak see "Specifying File Extensions".

A backup file of the source is always written, but you can request that it be deleted at the end of processing if there were no errors. This is risky unless the source code is being maintained with a source code control system. โš ๏ธ risky behavior fr fr

So to say "yeah delete that backup when we're done" you drop one forward slash, /, into the extension. If any text is left over once that slash gets removed, that leftover text becomes the backup file extension โ€” and heads up, the backup is always created, it just only gets deleted if there were zero errors. ๐Ÿ’…

Here are some examples:

  Parameter          Extension      Backup File Treatment
  -bext=bak         .bak            Keep (same as default behavior)
  -bext='/'         .bak            Delete if no errors
  -bext='/backup'   .backup         Delete if no errors
  -bext='original/' .original       Delete if no errors
  • -bm=s, --backup-method=s โ€” okay so bestie, this one you should not normally reach for, but it exists in case stuff goes sideways while transitioning from an older implementation of the backup logic to a newer one. The newer implementation is the default and you get it with -bm='copy'. The older one is -bm='move'. The tea โ˜•: the older implementation made the backup by moving the input file to the backup file, and the newer one makes the backup by copying the input file. The newer implementation preserves the file system inode value, which may dodge problems with other software running at the same time. This change was made as part of issue git #103 at github.
  • -w, --warning-output โ€” setting -w means any non-critical warning messages get reported as errors instead. That includes messages about possible pod problems, possibly bad starting indentation level, and cautions about indirect object usage. The default, -nw or --nowarning-output, does not include these warnings. ๐Ÿ™ˆ
  • -q, --quiet โ€” deactivates error messages (this is for when you're running under an editor).

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

:n1,n2!perltidy -q

where "n1,n2" represents the selected text. Without the -q flag, any error message may mess up your screen, so be prepared to use your "undo" key. ๐Ÿ˜ญ

  • -log, --logfile โ€” saves the .LOG file, which has so many useful diagnostics. Perltidy always creates a .LOG file, but by default it gets deleted unless a program bug is suspected. Setting the -log flag forces the log file to be saved. ๐Ÿ‘‘
  • -g=n, --logfile-gap=n โ€” sets the maximum interval between input code lines in the logfile. The purpose of this flag is to help debug nesting errors. The value of "n" is optional. If you set the flag -g without a value for "n", it's taken to be 1, meaning every single line gets written to the log file. This can be helpful if you're hunting down a brace, paren, or bracket nesting error. ๐Ÿ”

Setting -g also causes the logfile to be saved, so you don't have to also include -log.

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

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

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

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

  • -pro=filename or --profile=filename โ€” to simplify testing and switching .perltidyrc files, this command may be used to specify a configuration file which will override the default name of .perltidyrc. There must not be a space on either side of the '=' sign. For example, the line
perltidy -pro=testcfg

would cause file testcfg to be used instead of the default .perltidyrc.

A pathname that begins with three dots, e.g. .../.perltidyrc, indicates that the file should be searched for starting in the current directory and working upwards. This makes it easier to have multiple projects each with their own .perltidyrc in their root directories. ๐Ÿฆ‹

  • -opt, --show-options โ€” writes a list of all options used to the .LOG file. Please see --dump-options for a simpler way to do this.
  • -f, --force-read-binary โ€” forces perltidy to process binary files. To avoid producing excessive error messages, perltidy skips files identified by the system as non-text. However, valid perl scripts containing binary data may sometimes be identified as non-text, and this flag forces perltidy to process them. ๐Ÿ’ช
  • -ast, --assert-tidy โ€” this flag asserts that the input and output code streams are identical, or in other words that the input code is already 'tidy' according to the formatting parameters. If that's not the case, an error message noting this is produced. This error message will cause the process to return a non-zero exit code. The test for this is made by comparing an MD5 hash value for the input and output code streams. This flag has no other effect on the functioning of perltidy. This might be useful for certain code maintenance operations. Note: you will not see this message if you have error messages turned off with the -quiet flag. โœจ
  • -asu, --assert-untidy โ€” this flag asserts that the input and output code streams are different, or in other words that the input code is 'untidy' according to the formatting parameters. If that's not the case, an error message noting this is produced. This flag has no other effect on the functioning of perltidy.
  • -tos=n, --timeout-in-seconds=n โ€” when the standard input supplies the input stream, and the input has not been received within n seconds, perltidy will end with a timeout message. The intention is to catch a situation where perltidy is accidentally invoked without a file to process and therefore waits for input from the system standard input (stdin), which never arrives. The default is n=10 seconds. This check can be turned off with n=0. โฐ

๐ŸŒˆ FORMATTING OPTIONS ๐ŸŒˆ

โœจ Basic Options โœจ

  • -fmt=s, --format=s โ€” if --format=tidy (the default) then perltidy will reformat the input file, and if --format=html then perltidy will produce html output.

For convenience, the abbreviation --tidy is equivalent to --format=tidy, and -html is equivalent to --format=html.

  • --notidy โ€” this flag disables all formatting and causes the input to be copied unchanged to the output, except for possible changes in line ending characters and any pre- and post-filters. This can be useful in conjunction with a hierarchical set of .perltidyrc files to avoid unwanted code tidying. See also "Skipping Selected Sections of Code" for a way to avoid tidying specific sections of code. ๐Ÿ˜Œ
  • -i=n, --indent-columns=n โ€” use n columns per indentation level (default n=4).
  • -l=n, --maximum-line-length=n โ€” the default maximum line length is n=80 characters. Perltidy will try to find line break points to keep lines below this length. However, long quotes and side comments may cause lines to exceed this length. And long lines may sometimes be broken at a length less than n characters because some of the line break decisions employ small tolerances to prevent formatting instabilities.

The default length of 80 comes from the past when this was the standard CRT screen width. Many programmers prefer to increase this to something like 120.

Setting -l=0 is equivalent to setting -l=(a very large number). But this is not recommended because, for example, a very long list will be formatted in a single long line. ๐Ÿ˜ฌ

  • -vmll, --variable-maximum-line-length โ€” a problem arises using a fixed maximum line length with very deeply nested code and data structures, because eventually the amount of leading whitespace used for indicating indentation takes up most or all of the available line width, leaving little or no space for the actual code or data. One solution is to use a very long line length. Another solution is to use the -vmll flag, which basically tells perltidy to ignore leading whitespace when measuring the line length.

To be precise, when the -vmll parameter is set, the maximum line length of a line of code will be M+L*I, where

      M is the value of --maximum-line-length=M (-l=M), default 80,
      I is the value of --indent-columns=I (-i=I), default 4,
      L is the indentation level of the line of code

When this flag is set, the choice of breakpoints for a block of code should be essentially independent of its nesting depth. However, the absolute line lengths, including leading whitespace, can still be arbitrarily large. This problem can be avoided by including the next parameter.

The default is not to do this (-nvmll).

  • -wc=n, --whitespace-cycle=n โ€” this flag also addresses problems with very deeply nested code and data structures. When the nesting depth exceeds the value n the leading whitespace will be reduced and start at a depth of 1 again. The result is that blocks of code will shift back to the left rather than moving arbitrarily far to the right. This occurs cyclically to any depth. ๐ŸŒ€

For example if one level of indentation equals 4 spaces (-i=4, the default), and one uses -wc=15, then if the leading whitespace on a line exceeds about 4*15=60 spaces it will be reduced back to 4*1=4 spaces and continue increasing from there. If the whitespace never exceeds this limit the formatting remains unchanged.

The combination of --variable-maximum-line-length and --whitespace-cycle=n provides a solution to the problem of displaying arbitrarily deep data structures and code in a finite window, although --whitespace-cycle=n may of course be used without --variable-maximum-line-length.

The default is not to use this, which can also be indicated using -wc=0.

๐ŸŽ€ Tabs ๐ŸŽ€

Using tab characters will almost certainly lead to future portability and maintenance problems, so the default and recommendation is not to use them. For those who prefer tabs, however, there are two different options.

Okay so the whole tab situation first, bestie, because it's important: except for possibly introducing tab indentation characters (as outlined below), perltidy does not introduce any tab characters into your file, and it removes any tabs from the code (unless you specifically ask it not to, with --freeze-whitespace). But if you have tabs in your comments, quotes, or here-documents? Those stay. Untouched. Handled. ๐Ÿ’…


  • -et=n, --entab-leading-whitespace โ€” every n leading space characters that the formatting process produces get replaced by one single tab character. โœจ

The formatting process itself works with space characters โ€” the -et=n parameter is applied as a last step, after formatting is complete, to convert leading spaces into tabs. So before you start living your tab life, it is essential to first get the indentation controls set exactly how you want them without tabs, particularly these two:

  • --indent-columns=n (or -i=n)
  • --continuation-indentation=n (or -ci=n)

The value of the integer n can be any value, but you can coordinate it with the number of spaces used for indentation. For example, -et=4 -ci=4 -i=4 will produce one tab for each indentation level and one for each continuation indentation level. You may also want to coordinate the value of n with what your display software assumes for the spacing of a tab. ๐Ÿ‘€

The default is not to use this, which you can also signal with -et=0.

  • -t, --tabs โ€” this flag causes one leading tab character to be inserted for each level of indentation. ๐ŸŒˆ
Certain other features are incompatible with this option, and if these options are also given, then a warning message will be issued and this flag will be unset. One example is the --line-up-parentheses option.

This flag is retained for backwards compatibility, but if you use tabs, the --entab-leading-whitespace=n flag is the recommended one. And if both --tabs and --entab-leading-whitespace=n are set, then --entab-leading-whitespace=n is used. Periodt, it wins.

  • -dt=n, --default-tabsize=n โ€” if the first line of code passed to perltidy contains leading tabs but no tab scheme is specified for the output stream, then perltidy has to guess how many spaces correspond to each leading tab. ๐Ÿ•ต๏ธโ€โ™€๏ธ This number of spaces n corresponding to each leading tab of the input stream may be specified with -dt=n. The default is n=8.

This flag has no effect if a tab scheme is specified for the output stream, because then the input stream is assumed to use the same tab scheme and indentation spaces as the output stream (any other assumption would lead to unstable editing). So, like, don't worry about it in that case.

  • -io, --indent-only โ€” this flag deactivates all whitespace and line break changes within non-blank lines of code. ๐Ÿ™ˆ When it's in effect, the only change to the script will be to the indentation and to the number of blank lines. And any flags controlling whitespace and newlines will be ignored.

You might want this if you are perfectly happy with your whitespace and line breaks, and you merely want perltidy to handle the indentation. (It also speeds up perltidy by well over a factor of two, so it might be useful when perltidy is merely being used to help find a brace error in a large script.) ๐Ÿ’–

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

If you also want to keep your existing blank lines exactly as they are, you can add --freeze-blank-lines.

With this option perltidy is still free to modify the indenting (and outdenting) of code and comments as it normally would. If you also want to prevent long comment lines from being outdented, you can add either --nooutdent-long-lines (-noll) or --maximum-line-length=0 (l=0).

Setting this flag will prevent perltidy from doing any special operations on closing side comments. You may still delete all side comments however when this flag is in effect. ๐Ÿ‘‘

  • -enc=s, --character-encoding=s โ€” this flag tells perltidy whether the input data stream uses a character encoding. ๐Ÿฆ‹

Perltidy does not look for the encoding directives in the source stream, such as use utf8, and instead relies on this flag to determine the encoding. (This is because perltidy often works on snippets of code rather than complete files, so it cannot rely on use utf8 directives.) Consequently perltidy is likely to encounter problems formatting a file which is only partially encoded.

The possible values for s are:

  • -enc=none if no encoding is used, or
  • -enc=utf8 for encoding in utf8
  • -enc=guess if perltidy should guess between these two possibilities.

The value none causes the stream to be processed without special encoding assumptions. This is appropriate for files which are written in single-byte character encodings such as latin-1.

The value utf8 causes the stream to be read and written as UTF-8. If the input stream cannot be decoded with this encoding then processing is not done. ๐Ÿšซ

The value guess tells perltidy to guess between either utf8 encoding or no encoding (meaning one character per byte). The guess option uses the Encode::Guess module which has been found to be reliable at detecting if a file is encoded in utf8 or not.

The current default is guess.

The abbreviations -utf8 or -UTF8 are equivalent to -enc=utf8, and the abbreviation -guess is equivalent to -enc=guess. So to process a file named file.pl which is encoded in UTF-8 you can use:

perltidy -utf8 file.pl

or

perltidy -guess file.pl

or simply

perltidy file.pl

since -guess is the default. ๐Ÿ˜Œ

To process files with an encoding other than UTF-8, it would be necessary to write a short program which calls the Perl::Tidy module with some pre- and post-processing to handle decoding and encoding.

  • -eos=s, --encode-output-strings=s โ€” this flag was added to resolve an issue involving the interface between Perl::Tidy and calling programs, and in particular Code::TidyAll (tidyall). ๐Ÿซถ

If you only run the perltidy binary this flag has no effect. If you run a program which calls the Perl::Tidy module and receives a string in return, then the meaning of the flag is as follows:

  • The setting -eos means Perl::Tidy should encode any string which it decodes. This is the default because it makes perltidy behave well as a filter, and is the correct setting for most programs.
  • The setting -neos means that a string should remain decoded if it was decoded by Perl::Tidy. This is only appropriate if the calling program will handle any needed encoding before outputting the string.

The default was changed from -neos to -eos in versions after 20220217. If this change causes a program to start running incorrectly on encoded files, an emergency fix might be to set -neos. ๐Ÿšจ Additional information can be found in the man pages for the Perl::Tidy module and also in <https://github.com/perltidy/perltidy/blob/master/docs/eos_flag.md>.

  • -gcs, --use-unicode-gcstring โ€” this flag controls whether or not perltidy may use module Unicode::GCString to obtain accurate display widths of wide characters. ๐Ÿ’œ The default is --nouse-unicode-gcstring.

If this flag is set, and text is encoded, perltidy will look for the module Unicode::GCString and, if found, will use it to obtain character display widths. This can improve displayed vertical alignment for files with wide characters. It is a nice feature but it is off by default to avoid conflicting formatting when there are multiple developers. Perltidy installation does not require Unicode::GCString, so users wanting to use this feature need to set this flag and also to install Unicode::GCString separately. ๐ŸŒธ

If this flag is set and perltidy does not find module Unicode::GCString, a warning message will be produced and processing will continue but without the potential benefit provided by the module.

Also note that actual vertical alignment depends upon the fonts used by the text display software, so vertical alignment may not be optimal even when Unicode::GCString is used. iykyk, fonts are chaotic. ๐Ÿ˜ญ

  • -ole=s, --output-line-ending=s โ€” where s="win", "dos", "unix", or "mac". This flag tells perltidy to output line endings for a specific system. โญ Normally, perltidy writes files with the line separator character of the host system. The "win" and "dos" flags have an identical result.
  • -ple, --preserve-line-endings โ€” this flag tells perltidy to write its output files with the same line endings as the input file, if possible. ๐ŸŽ€ It should work for dos, unix, and mac line endings. It will only work if perltidy input comes from a filename (rather than stdin, for example). If perltidy has trouble determining the input file line ending, it will revert to the default behavior of using the line ending of the host system.
  • -atnl, --add-terminal-newline โ€” this flag, which is enabled by default, allows perltidy to terminate the last line of the output stream with a newline character, regardless of whether or not the input stream was terminated with a newline character. โœจ If this flag is negated, with -natnl, then perltidy will add a terminal newline to the the output stream only if the input stream is terminated with a newline.

Negating this flag may be useful for manipulating one-line scripts intended for use on a command line.

(yes, the original really says "to the the output stream" โ€” we don't fix typo heritage here, we just report it ๐Ÿซก)
  • -it=n, --iterations=n โ€” this flag causes perltidy to do n complete iterations. ๐Ÿ”

The reason for this flag is that code formatting is an iterative process and in some cases the output from perltidy can be different if it is applied a second time. For most purposes the default of n=1 should be satisfactory. However n=2 can be useful when a major style change is being made, or when code is being beautified on check-in to a source code control system. It has been found to be extremely rare for the output to change after 2 iterations. If a value n greater than 2 is input then a convergence test will be used to stop the iterations as soon as possible, almost always after 2 iterations. See the next item for a simplified iteration control. ๐Ÿ‘€

This flag has no effect when perltidy is used to generate html.

  • -conv, --converge โ€” okay so this one is literally just -it=4 with a cute name ๐Ÿ’… it exists to make iteration control simpler. Perltidy will vibe check for convergence and stop iterating ASAP. Default is -nconv (no convergence check, no thoughts head empty). Heads up though: using -conv will approximately double your run time, because you typically need one extra iteration to verify convergence. No extra iterations are needed if no new line breaks get made, and two extra iterations are occasionally needed when reformatting complex code structures, like deeply nested ternary statements. So it's giving "worth it but make it expensive" โœจ

๐ŸŽ€ Code Indentation Control ๐ŸŽ€

  • -ci=n, --continuation-indentation=n โ€” continuation indentation is the extra indentation spaces applied when a long line gets broken. Default is n=2, and here's the glow-up illustrated:
 my $level =   # -ci=2
   ( $max_index_to_go >= 0 ) ? $levels_to_go[0] : $last_output_level;

Same example, but with n=0, and ngl bestie it's a little harder to read:

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

The value you give to -ci also gets used by some commands when a small space is required. Examples are the commands for outdenting labels, --outdent-labels (-ola), and control keywords, --outdent-keywords (-okw).

When you're not using the default values, it's recommended that either:

  1. the value n given with -ci=n be no more than about one-half of the number of spaces assigned to a full indentation level on the -i=n command, or
  2. the flag --extended-continuation-indentation is used (see next section ๐Ÿ‘‡).
  • -xci, --extended-continuation-indentation โ€” this flag lets perltidy use some improvements that have been made to its indentation model. One of the things it does is "extend" continuation indentation deeper into structures, hence the name, iykyk. The improved indentation is particularly noticeable when the flags -ci=n and -i=n use the same value of n. There are no significant disadvantages to using this flag, but to avoid disturbing existing formatting the default is not to use it: -nxci.

Please see the section "-pbp, --perl-best-practices" for an example of how this flag can improve the formatting of ternary statements. It can also improve indentation of some multiline qw lists as shown below. Look at the difference, it's lowkey iconic:

        # perltidy
        foreach $color (
            qw(
            AntiqueWhite3 Bisque1 Bisque2 Bisque3 Bisque4
            SlateBlue3 RoyalBlue1 SteelBlue2 DeepSkyBlue3
            ),
            qw(
            LightBlue1 DarkSlateGray1 Aquamarine2 DarkSeaGreen2
            SeaGreen1 Yellow1 IndianRed1 IndianRed2 Tan1 Tan4
            )
          )

        # perltidy -xci
        foreach $color (
            qw(
                AntiqueWhite3 Bisque1 Bisque2 Bisque3 Bisque4
                SlateBlue3 RoyalBlue1 SteelBlue2 DeepSkyBlue3
            ),
            qw(
                LightBlue1 DarkSlateGray1 Aquamarine2 DarkSeaGreen2
                SeaGreen1 Yellow1 IndianRed1 IndianRed2 Tan1 Tan4
            )
          )
  • -mci, --minimize-continuation-indentation โ€” this flag lets perltidy remove continuation indentation in some special cases where it is not really unnecessary. For a simple example, the default formatting for the following snippet is:
    # perltidy -nmci
    $self->blurt( "Error: No INPUT for type '$type', typekind '"
          . $type->xstype
          . "' found" );

The second and third lines are one level deep in a container, and are also statement continuations, so they get indented by the sum of the full indentation -i value plus the continuation indentation -ci value. If this flag is set, the indentation is reduced by -ci spaces, giving us this:

    # perltidy -mci
    $self->blurt( "Error: No INPUT for type '$type', typekind '"
        . $type->xstype
        . "' found" );

This flag is off by default. ๐Ÿซถ

  • -sil=n --starting-indentation-level=n โ€” by default, perltidy examines the input file and tries to determine the starting indentation level. While it is often zero, it may not be zero for a code snippet being sent from an editing session.

To guess the starting indentation level, perltidy simply assumes that the indentation scheme used to create the code snippet is the same as is being used for the current perltidy process. This is the only sensible guess that can be made. It should be correct if this is true, but otherwise it probably won't be ๐Ÿ˜ญ For example, if the input script was written with -i=2 and the current perltidy flags have -i=4, the wrong initial indentation will be guessed for a code snippet which has non-zero initial indentation. Likewise, if an entabbing scheme is used in the input script and not in the current process, then the guessed indentation will be wrong.

If the default method does not work correctly, or you want to change the starting level, use -sil=n, to force the starting level to be n.

List indentation using --line-up-parentheses, -lp or --extended--line-up-parentheses, -xlp

These flags provide an alternative indentation method for list data. The original flag for this is -lp, but it has some limitations (explained below ๐Ÿ‘‡) which are avoided with the newer -xlp flag. So -xlp is probably the better choice for new work, but the -lp flag is retained to minimize changes to existing formatting. If you enter both -lp and -xlp, then -xlp will be used.

In the default indentation method perltidy indents lists with 4 spaces, or whatever value is specified with -i=n. Here is a small list formatted in this way:

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

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

    # perltidy -lp or -xlp
    @month_of_year = (
                       'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                       'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
    );

If the available line length (see -l=n ) does not permit this much space, perltidy will use less. For alternate placement of the closing paren, see the next section.

These flags have no effect on code BLOCKS, such as if/then/else blocks, which always use whatever is specified with -i=n.

Some limitations on these flags are:

  • A limitation on -lp, but not -xlp, occurs in situations where perltidy does not have complete freedom to choose line breaks. Then it may temporarily revert to its default indentation method. This can occur for example if there are blank lines, block comments, multiline quotes, or side comments between the opening and closing parens, braces, or brackets. It will also occur if a multiline anonymous sub occurs within a container, since that will impose specific line breaks (such as line breaks after statements).
  • For both the -lp and -xlp flags, any parameter which significantly restricts the ability of perltidy to choose newlines will conflict with these flags and will cause them to be deactivated. These include --indent-only, --freeze-newlines, --noadd-newlines, and --nodelete-old-newlines.
  • The -lp and -xlp options may not be used together with the -t tabs option. They may, however, be used with the -et=n tab method.

There are some potential disadvantages of this indentation method compared to the default method that should be noted:

  • The available line length can quickly be used up if variable names are long. This can cause deeply nested code to quickly reach the line length limit, and become badly formatted, much sooner than would occur with the default indentation method.
  • Since the indentation depends on the lengths of variable names, small changes in variable names can cause changes in indentation over many lines in a file. This means that minor name changes can produce significant file differences. This can be annoying and does not occur with the default indentation method.
ngl that second one is giving "one tiny rename, 400 line diff" and it's a whole mood ๐Ÿ’€

Some things that can be done to minimize these problems are:

  • Increase --maximum-line-length=n above the default n=80 characters if necessary.
  • If you use -xlp then long side comments can limit the indentation over multiple lines. Consider adding the flag --ignore-side-comment-lengths to prevent this, or minimizing the use of side comments.
  • Apply this style in a limited way. By default, it applies to all list containers (not just lists in parentheses). The next section describes how to limit this style to, for example, just function calls. The default indentation method will be applied elsewhere.

-lpil=s, --line-up-parentheses-inclusion-list and -lpxl=s, --line-up-parentheses-exclusion-list

The following discussion is written for -lp but applies equally to the newer -xlp version. By default, the -lp flag applies to as many containers as possible. The set of containers to which the -lp style applies can be reduced by either one of these two flags:

Use --line-up-parentheses-inclusion-list=s (-lpil=s) to specify the containers to which -lp applies, or

use --line-up-parentheses-exclusion-list=s (-lpxl=s) to specify the containers to which -lp does NOT apply.

Only one of these two flags may be used. Both flags can achieve the same result, but the -lpil=s flag is much easier to describe and use, and is recommended. The -lpxl=s flag was the original implementation and is only retained for backwards compatibility.

This list s for these parameters is a string with space-separated items. Each item consists of up to three pieces of information in this order: (1) an optional letter code (2) a required container type, and (3) an optional numeric code.

The only required piece of information is a container type, which is one of '(', '[', or '{'. For example the string

  -lpil='('

means only slay the -lp formatting on lists inside parentheses โ€” not on lists in square-brackets or braces, bestie. The exact same thing could also be said with

-lpxl = '[ {'

which is basically like "exclude lists inside square-brackets and braces", so what's left over? Lists inside parentheses. ๐Ÿ’…

Now โ€” there's a second optional lil piece of info you can hand over for parentheses: an alphanumeric letter, which narrows the selection even more depending on what kind of token sits immediately before the paren. The letters available rn are 'k', 'K', 'f', 'F', 'w', and 'W', and here's what they mean when matching whatever comes before an opening paren:

  • 'k' matches if the previous nonblank token is a perl keyword (things like 'if', 'while')
  • 'K' matches if 'k' does not โ€” i.e. the previous token is not a keyword
  • 'f' matches if the previous token is a function (not a keyword)
  • 'F' matches if 'f' does not
  • 'w' matches if either 'k' or 'f' match
  • 'W' matches if 'w' does not

For example:

-lpil = 'f('

means only apply -lp to function calls, and

-lpil = 'w('

means only apply -lp to parenthesized lists that follow a function or a keyword. ๐Ÿซถ

That last example could alternatively be written using the -lpxl=s flag as

-l lpxl = '[ { W('
oops โ€” keep it exactly as it is:
-lpxl = '[ { W('

which says: exclude -lp for lists within square-brackets, braces, and parens NOT preceded by a keyword or function. And honestly? The -lpil=s method is clearly easier to understand. No cap. ๐Ÿ˜Œ

You can also tack an optional numeric code onto any of the container types to refine the selection based on what's inside the container. The numeric codes are:

  • '0' or blank: no restriction is placed on container contents
  • '1' the container contents must be a simple list without sublists
  • '2' the container contents must be a simple list without sublists, without code blocks, and without ternary operators

For example,

-lpil = 'f(2'

means only apply -lp to function calls with simple lists (not containing any sublists, code blocks or ternary expressions). ๐ŸŽ€

  • -cti=n, --closing-token-indentation โ€” the -cti=n flag controls the indentation of a line that starts with a ), a ], or a non-block }. A line like that receives:
    • -cti = 0 no extra indentation (default)
    • -cti = 1 extra indentation such that the closing token aligns with its opening token.
    • -cti = 2 one extra indentation level if the line looks like: ); or ]; or };
    • -cti = 3 one extra indentation level always

The flags -cti=1 and -cti=2 work so well with the --line-up-parentheses (-lp) flag (that's the previous section, iykyk).

# perltidy -lp -cti=1
@month_of_year = (
                   'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                   'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
                 );

# perltidy -lp -cti=2
@month_of_year = (
                   'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                   'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
                 );
These flags are merely hints to the formatter and they may not always be followed. In particular, if -lp is not being used, the indentation for cti=1 is constrained to be no more than one indentation level. ๐Ÿ™ˆ

If you want, this control can be applied independently to each of the closing container token types. In fact, -cti=n is merely an abbreviation for -cpi=n -csbi=n -cbi=n, where: -cpi or --closing-paren-indentation controls )'s, -csbi or --closing-square-bracket-indentation controls ]'s, and -cbi or --closing-brace-indentation controls non-block }'s. ๐Ÿ’–

  • -icp, --indent-closing-paren โ€” the -icp flag is equivalent to -cti=2, described in the previous section. The -nicp flag is equivalent to -cti=0. They're included for backwards compatibility. ๐ŸŒธ
  • -icb, --indent-closing-brace โ€” the -icb option gives one extra level of indentation to a brace that terminates a code block. For example,
    if ($task) {
        yyy();
        }    # -icb
    else {
        zzz();
        }

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

  • -ils, --indent-leading-semicolon โ€” a line that begins with a leading semicolon will, by default, have the extra number of indentation spaces defined by --continuation-indentation=n. This extra indentation can be removed by setting -nils.
# default
$z = sqrt( $x**2 + $y**2 )

  ;    # <-- indented by ci spaces

# -nils
$z = sqrt( $x**2 + $y**2 )

;    # <-- not indented by ci spaces
Note that leading semicolons don't normally occur unless you asked for them with --break-at-old-semicolon-breakpoints or they got forced, like by a blank line as in this example. ๐Ÿ˜ญ
  • -nib, --non-indenting-braces โ€” normally, lines of code contained within a pair of block braces receive one additional level of indentation. This flag, which is enabled by default, causes perltidy to look for opening block braces which are followed by a special side comment. This special side comment is #<<< by default. If found, the code between this opening brace and its corresponding closing brace will not be given the normal extra indentation level. For example:
{ #<<<   a closure to contain lexical vars

my $var;  # this line does not get one level of indentation
...

}

# this line does not 'see' $var;

This can be useful, for example, when combining code from different files. Different sections of code can be placed within braces to keep their lexical variables from being visible to the end of the file. To keep the new braces from causing all of their contained code to be indented if you run perltidy, and possibly introducing new line breaks in long lines, you can mark the opening braces with this special side comment. ๐Ÿ‘‘

Only the opening brace needs to be marked, since perltidy knows where the closing brace is. Braces contained within marked braces may also be marked as non-indenting.

If your code happens to have some opening braces followed by '#<<<', and you don't want this behavior, you can use -nnib to deactivate it. To make it easy to remember, the default string is the same as the string for starting a format-skipping section. There's no confusion because in that case it's for a block comment rather than a side-comment. ๐Ÿฆ‹

The special side comment can be changed with the next parameter.

  • -nibp=s, --non-indenting-brace-prefix=s โ€” the -nibp=string parameter may be used to change the marker for non-indenting braces. The default is equivalent to -nibp='#<<<'. The string that you enter must begin with a # and should be in quotes as necessary to get past the command shell of your system. This string is the leading text of a regex pattern that is constructed by prepending a '^' and appending a '\s', so you must also include backslashes for characters to be taken literally rather than as patterns. ๐Ÿ’…

For example, to match the side comment '#++', the parameter would be

-nibp='#\+\+'
  • -olq, --outdent-long-quotes โ€” when -olq is set, lines which is a quoted string longer than the value maximum-line-length will have their indentation removed to make them more readable. This is the default. To prevent such out-denting, use -nolq. ๐ŸŒˆ
  • -oll, --outdent-long-lines โ€” this command is equivalent to the combination --outdent-long-quotes and --outdent-long-comments, and it's included for compatibility with previous versions of perltidy. The negation of this also works, -noll or --nooutdent-long-lines, and is equivalent to setting -nolq and -nolc. ๐Ÿ“

โœจ Outdenting Labels: -ola, --outdent-labels โœจ

This command will cause labels to be outdented by the number of spaces defined by --continuation-indentation=n, if possible. This is the default, bestie. For example:

        my $i;
      LOOP: while ( $i = <FOTOS> ) {
            chomp($i);
            next unless $i;
            fixit($i);
        }

Use -nola to prevent this. To control line breaks after labels see -bal=n, --break-after-labels=n. ๐ŸŽ€


โœจ Outdenting Keywords โœจ

-okw, --outdent-keywords

The command -okw will cause certain leading control keywords to be outdented by the number of spaces defined by --continuation-indentation=nspaces, if possible. By default, these keywords are "redo", "next", "last", "goto", and "return". The intention is to make these control keywords easier to see. To change this list of keywords being outdented, see the next section. ๐Ÿ‘€

For example, using perltidy -okw on the previous example gives:

        my $i;
      LOOP: while ( $i = <FOTOS> ) {
            chomp($i);
          next unless $i;
            fixit($i);
        }

Notice that the keyword next has been outdented. The default is not to do this. ๐Ÿ’€

Specifying Outdented Keywords: -okwl=string, --outdent-keyword-list=string

This command can be used to change the keywords which are outdented with the -okw command. The parameter string is a required list of perl keywords, which should be placed in quotes if there's more than one. By itself, it does not cause any outdenting to occur, so the -okw command is still required. ๐Ÿซถ

For example, the commands -okwl="next last redo goto" -okw will cause those four keywords to be outdented.


โœจ Whitespace Control โœจ

Whitespace refers to the blank space between variables, operators, and other code tokens. ๐Ÿฆ‹

  • -fws, --freeze-whitespace โ€” this flag causes your original whitespace to remain unchanged, and causes the rest of the whitespace commands in this section, the Code Indentation section, and the Comment Control section to be ignored. โ„๏ธ

๐Ÿ’… Tightness of curly braces, parentheses, and square brackets

okay so let's talk tightness โ€” and bestie, here "tightness" literally just means how close a pair of enclosing cuties (parens, brackets, braces) hugs the stuff inside. A number like 0, 1, or 2 sets the vibe, where 0 is the loosest hug and 2 is the tightest squeeze. Oh and important: spaces inside containers are always symmetric, so if there's a space after a ( then there's coming a space before the matching ). no lopsided fits, periodt. ๐Ÿ’–

The -pt=n or --paren-tightness=n parameter runs the space inside parens. Watch the three values do their thing:

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

When n is 0, there is always a space to the right of a ( and to the left of a ). For n=2 there is never a space. For n=1, the default, there is a space unless the thing inside the parens is a single token โ€” like an identifier or a quoted string. slay.

Likewise, -sbt=n or --square-bracket-tightness=n controls the space within square brackets, like so:

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

Curly braces that don't hold code blocks are run by -bt=n or --brace-tightness=n.

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

And finally, curly braces that do hold blocks of code are run by -bbt=n or --block-brace-tightness=n, shown below (-bbt=0 is the default).

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

To make life easier when all the tightness flags share the same value n, there's -act=n or --all-containers-tightness=n โ€” a lil abbreviation for the whole combo -pt=n -sbt=n -bt=n -bbt=n. one parameter, all the vibes. โœจ

-mutt=s, --multiple-token-tightness=s

To recap: the tightness controls from the section above have three possible integer values โ€” 0, 1, and 2 โ€” where n=0 always adds a space and n=2 never adds a space.

The default value n=1 adds space only if the container holds multiple tokens. But some perltidy tokens can be kinda long, and sometimes you'd rather space a few of them out as if they were multiple tokens. That's what this parameter is for, bestie.

For example, in the following expression the qw list is a single token, so the default formatting doesn't put spaces within the square brackets:

my $rlist = [qw(alpha beta gamma)];

You can change that with:

# perltidy -mutt='qw'
my $rlist = [ qw(alpha beta gamma) ];

This tells perltidy to space a qw list as if it were multiple tokens when the default tightness is used. ๐Ÿ‘‘

The parameter s may contain any of the following perl operators:

qw q qq qx qr s y tr m

Other possible specifications are

  • q* โ€” all of the above operators
  • Q โ€” all of the above plus any quoted text
  • h โ€” a here-doc target, such as '<<EOT'
  • <<>> โ€” the double-diamond operator

A symbol may be negated by putting a carat ^ symbol in front of it. The double-diamond operator is always included unless it's negated this way.

-xbt, --extended-block-tightness

So there are two controls for spacing within curly braces: --block-brace-tightness=n for code block braces, and --brace-tightness=n for all the other braces.

But there's a lil fuzziness in how that split works, because the curly braces perltidy considers to be "code blocks" for formatting purposes โ€” like for highlighting code structure โ€” exclude some of the small code blocks Perl uses mainly for isolating terms. These include curly braces following a keyword where an indirect object might show up, or curly braces following a type symbol. For example, perltidy does not mark these braces as code block braces:

print {*STDERR} $message;
return ${$foo};

Consequently, the spacing inside these small braced containers by default follows --brace-tightness=n rather than --block-brace-tightness=n, like you might've expected. ๐Ÿ™ˆ

If you want, small blocks like these can instead follow the spacing defined by --block-brace-tightness=n by setting --extended-block-tightness. Exactly which types of small blocks this applies to is controlled by a companion parameter, described in the next section.

Note that if the two flags --block-brace-tightness=n and --brace-tightness=n have the same value n, then there'd be no reason to set this flag. iykyk.

-xbtl=s, --extended-block-tightness-list=s

The previous parameter --extended-block-tightness (-xbt) can be made to apply to curly braces preceded by any of the keywords

print printf exec system say

and/or the special symbols

$ @ % & * $#

The parameter string s may hold a selection of these keywords and symbols to indicate the brace types that --extended-block-tightness applies to. For convenience, all the keywords can be selected with 'k', and all the special symbols can be selected with 't'. The default is equivalent to -xbtl='k', which selects all of the keywords. ๐ŸŽ€

Examples:

-xbtl='k'          # selects just the keywords [DEFAULT]
-xbtl="t"          # selects just the special type symbols
-xbtl="k t"        # selects all keywords and symbols, or simply
-xbtl="kt"         # selects all keywords and symbols
-xbtl="print say"  # selects just keywords B<print> and B<say>:

Here are some formatting examples using the default values of --brace-tightness=n and --block-brace-tightness=n. Note that in these examples $ref is in block braces but $key is not.

# default formatting
print {*STDERR} $message;
my $val = ${$ref}{$key};

# perltidy -xbt           or
# perltidy -xbt -xbtl=k
print { *STDERR } $message;
my $val = ${$ref}{$key};

# perltidy -xbt -xbtl=t
print {*STDERR} $message;
my $val = ${ $ref }{$key};

# perltidy -xbt -xbtl=kt
print { *STDERR } $message;
my $val = ${ $ref }{$key};

And finally, note that this parameter only changes the way the --extended-block-tightness parameter works. It has no effect unless --extended-block-tightness is actually set. fr fr.

-tso, --tight-secret-operators

The flag -tso makes certain perl token sequences (secret operators ๐Ÿคซ) that could be considered a single operator get formatted "tightly" โ€” as in, no spaces. The operators currently modified by this flag are:

0+  +0  ()x!! ~~<>  ,=>   =( )=

For example the sequence 0 +, which converts a string to a number, would be formatted without a space: 0+ when the -tso flag is set. This flag is off by default.

-sts, --space-terminal-semicolon

Some programmers like a space before all terminal semicolons. The default is no such space, and that's indicated with -nsts or --nospace-terminal-semicolon.

        $i = 1 ;     #  -sts
        $i = 1;      #  -nsts   (default)

-sfs, --space-for-semicolon

Semicolons inside for loops can sometimes be hard to see, especially when commas are also hanging around. This option puts spaces on both sides of those special semicolons, and it's the default. Use -nsfs or --nospace-for-semicolon to turn it off.

for ( @a = @$ap, $u = shift @a ; @a ; $u = $v ) {  # -sfs (default)
for ( @a = @$ap, $u = shift @a; @a; $u = $v ) {    # -nsfs

-asc, --add-semicolons

Setting -asc lets perltidy add any missing optional semicolon at the end of a line that's followed by a closing curly brace on the next line. This is the default, and you can deactivate it with -nasc or --noadd-semicolons.

-dsm, --delete-semicolons

Setting -dsm lets perltidy delete extra semicolons that are simply empty statements. This is the default, and you can deactivate it with -ndsm or --nodelete-semicolons. (Such semicolons are not deleted, however, if they would promote a side comment to a block comment.)

-aws, --add-whitespace

Setting this option lets perltidy add certain whitespace to improve code readability. This is the default. If you don't want any whitespace added, but you're fine with some whitespace getting deleted, use -naws. (Use --freeze-whitespace (-fws) to leave whitespace completely unchanged.) ๐ŸŒธ

-dws, --delete-old-whitespace

Setting this option lets perltidy remove optional whitespace between characters in the input file. The default is to not do this (-nodelete-old-whitespace). This parameter doesn't do much on its own. But paired with --noadd-whitespace it'll cause most of the whitespace in a file to get removed. ๐Ÿ’€

Detailed whitespace controls around tokens

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

  • -wls=s or --want-left-space=s,
  • -nwls=s or --nowant-left-space=s,
  • -wrs=s or --want-right-space=s,
  • -nwrs=s or --nowant-right-space=s.

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

To illustrate how these are used, suppose you want no space on either side of the token types = + - / *. The following two parameters would specify that:

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

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

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

becomes this:

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

okay so real talk ๐Ÿ’… these params are like, hints to perltidy, not hard-and-fast rules, because perltidy has to go around resolving beef between them and, like, every other rule it's running. and one of the conflicts that can pop off is this: between two tokens, the left token is like "gimme a space" and the right one is like "no <3." and in that case? the token that doesn't want the space wins. periodt.

to build this kind of input you literally need a full list of all the token types. you can get one with the command --dump-token-types. also try the -D flag on a lil snippet of code and peek at the .DEBUG file to see the tokenization. it's giving backstage pass ๐ŸŽ€

so to illustrate โ€” suppose we do not want a space after a colon that introduces a sub attribute. we gotta know its type. it's not a colon, because colon is the type of a ternary operator. the output of --dump-token-types says it's token type 'A'. to verify, we can run perltidy -D on a short piece of code containing such a colon, like

sub foo : lvalue;

this produces a .DEBUG file which contains

1: sub foo : lvalue;
1: SSSSSSSbAbwwwwww;

the top line is the input, and the bottom line shows the token types. the 'A' beneath the colon verifies that it's type A. slay.

so to prevent a space on the right of this colon we can use

# perltidy -nwrs='A'
sub foo :lvalue;
WARNING bestie be sure to put these tokens in quotes so your command shell doesn't misinterpret them ๐Ÿ˜ญ

๐Ÿซถ Note1: Perltidy does always follow whitespace controls

the various parameters controlling whitespace within a program are requests which perltidy follows as well as it possibly can โ€” but there are a bunch of situations where changing whitespace could change program behavior, and in those cases it justโ€ฆ doesn't. some of these are obvious; for example, we should not remove the space between the two plus symbols in '$x+ +$y' to avoid creating a '++' operator. some are more subtle and involve the whitespace around bareword symbols and locations of possible filehandles. for example, consider the problem of formatting the following subroutine:

sub print_div {
   my ($x,$y)=@_;
   print $x/$y;
}

suppose the user requests that / signs have a space to the left but not to the right. perltidy will refuse to do this, but if this were done the result would be

sub print_div {
    my ($x,$y)=@_;
    print $x /$y;
}

if formatted in this way, the program will not run (at least with recent versions of perl) because the $x is taken to be a filehandle and / is assumed to start a quote. in a complex program, there might happen to be a / which terminates the multiline quote without a syntax error, allowing the program to run โ€” but not as intended ๐Ÿ˜ญ

related issues arise with other binary operator symbols, such as + and -, and in older versions of perl there could be problems with ternary operators. so to avoid changing program behavior, perltidy has the simple rule that whitespace around possible filehandles is left unchanged. likewise, whitespace around unknown barewords is left unchanged. the reason is that if the barewords are defined in other modules, or in code that has not even been written yet, perltidy will not have seen their prototypes and must treat them cautiously. it's giving "i don't know her, so i'm not gonna touch her" โœจ

in perltidy this is implemented in the tokenizer by marking token following a print keyword as a special type Z. when formatting is being done, whitespace following this token type is generally left unchanged as a precaution against changing program behavior. this is excessively conservative but simple and easy to implement. keywords which are treated similarly to print include printf, sort, exec, system. changes in spacing around parameters following these keywords may have to be made manually. for example, the space, or lack of space, after the parameter $foo in the following line will be unchanged in formatting.

system($foo );
system($foo);

to find if a token is of type Z you can use perltidy -DEBUG. for the first line above the result is

1: system($foo );
1: kkkkkk{ZZZZb};

which shows that system is type k (keyword) and $foo is type Z. iconic detective work ๐Ÿ”


๐Ÿ’” Note2: Perltidy's whitespace rules are not perfect

despite these precautions, it is still possible to introduce syntax errors with some asymmetric whitespace rules, particularly when call parameters are not placed in containing parens or braces ๐Ÿ™ˆ for example, the following two lines will be parsed by perl without a syntax error:

# original programming, syntax ok
my @newkeys = map $_-$nrecs+@data, @oldkeys;

# perltidy default, syntax ok
my @newkeys = map $_ - $nrecs + @data, @oldkeys;

but the following will give a syntax error:

# perltidy -nwrs='-'
my @newkeys = map $_ -$nrecs + @data, @oldkeys;

for another example, the following two lines will be parsed without syntax error:

# original programming, syntax ok
for my $severity ( reverse $LOWEST+1 .. $HIGHEST ) { ...  }

# perltidy default, syntax ok
for my $severity ( reverse $LOWEST + 1 .. $HIGHEST ) { ... }

but the following will give a syntax error:

# perltidy -nwrs='+', syntax error:
for my $severity ( reverse $LOWEST +1 .. $HIGHEST ) { ... }

to avoid subtle parsing problems like this, it is best to avoid spacing a binary operator asymmetrically with a space on the left but not on the right. noted bestie ๐Ÿ“


๐Ÿ”ค Space between specific keywords and opening paren

when an opening paren follows a Perl keyword, no space is introduced after the keyword, unless it is (by default) one of these:

my local our state and or xor err eq ne if else elsif until unless
while for foreach return switch case given when catch

these defaults can be modified with two commands:

  • -sak=s or --space-after-keyword=s โ€” adds keywords.
  • -nsak=s or --nospace-after-keyword=s โ€” removes keywords.

where s is a list of keywords (in quotes if necessary). for example,

my ( $a, $b, $c ) = @_;    # default
my( $a, $b, $c ) = @_;     # -nsak="my local our"

the abbreviation -nsak='*' is equivalent to including all of the keywords in the above list.

when both -nsak=s and -sak=s commands are included, the -nsak=s command is executed first. for example, to have space after only the keywords (my, local, our) you could use -nsak="*" -sak="my local our".

to put a space after all keywords, see the next item ๐Ÿ‘‘


๐Ÿ”ค Space between all keywords and opening parens

when an opening paren follows a function or keyword, no space is introduced after the keyword except for the keywords noted in the previous item. to always put a space between a function or keyword and its opening paren, use the command:

  • -skp or --space-keyword-paren

you may also want to use the flag -sfp (next item) too ๐ŸŒธ


๐Ÿ”ค Space between all function names and opening parens

when an opening paren follows a function the default and recommended formatting is not to introduce a space. to cause a space to be introduced use:

  • -sfp or --space-function-paren
myfunc( $a, $b, $c );    # default
myfunc ( $a, $b, $c );   # -sfp

you will probably also want to use the flag -skp (previous item) too.

the parameter is not recommended because spacing a function paren can make a program vulnerable to parsing problems by Perl. for example, the following two-line program will run as written but will have a syntax error if reformatted with -sfp:

if ( -e filename() ) { print "I'm here\n"; }
sub filename { return $0 }

in this particular case the syntax error can be removed if the line order is reversed, so that Perl parses 'sub filename' first. ๐Ÿ’€


๐Ÿ“ -fpva or --function-paren-vertical-alignment

a side-effect of using the -sfp flag is that the parens may become vertically aligned. for example,

# perltidy -sfp
myfun     ( $aaa, $b, $cc );
mylongfun ( $a, $b, $c );

this is the default behavior. to prevent this alignment use -nfpva:

# perltidy -sfp -nfpva
myfun ( $aaa, $b, $cc );
mylongfun ( $a, $b, $c );

๐Ÿ“ -spp=n or --space-prototype-paren=n

this flag can be used to control whether a function prototype is preceded by a space. for example, the following prototype does not have a space.

sub usage();

this integer n may have the value 0, 1, or 2 as follows:

-spp=0 means no space before the paren
-spp=1 means follow the example of the source code [DEFAULT]
-spp=2 means always put a space before the paren

the default is -spp=1, meaning that a space will be used if and only if there is one in the source code. given the above line of code, the result of applying the different options would be:

        sub usage();    # n=0 [no space]
        sub usage();    # n=1 [default; follows input]
        sub usage ();   # n=2 [space]

๐Ÿ“ -ssp=n or --space-signature-paren=n

this flag is analogous to the previous except that it applies to the space before the opening paren of a sub signature rather than a sub prototype.

for example, consider the following line:

sub circle( $xc, $yc, $rad )

this space before the opening paren can be controlled with integer n which may have the value 0, 1, or 2 with these meanings:

-ssp=0 means no space before the paren
-ssp=1 means follow the example of the source code [DEFAULT]
-ssp=2 means always put a space before the paren

the default is -ssp=1, meaning that will be a space in the output if, and only if, there is one in the input. given the above line of code, the result of applying the different options would be:

sub circle( $xc, $yc, $rad )   # n=0 [no space]
sub circle( $xc, $yc, $rad )   # n=1 [default; same as input]
sub circle ( $xc, $yc, $rad )  # n=2 [space]
  • -kpit=n, --keyword-paren-inner-tightness=n โ€” okay so bestie, this one controls the space inside an opening paren when that paren comes right after a certain keyword ๐Ÿ’…. And the space inside the matching closing paren gets treated the exact same way (balanced, periodt). This parameter is a big deal โ€” it takes precedence over any other paren spacing rules. The values of n go like this:
    • -kpit=0 means always put a space (not tight)
    • -kpit=1 means ignore this parameter [default]
    • -kpit=2 means never put a space (tight)

To illustrate, here's the same snippet formatted three ways:

    if ( seek( DATA, 0, 0 ) ) { ... }    # perltidy (default)
    if (seek(DATA, 0, 0)) { ... }        # perltidy -pt=2
    if ( seek(DATA, 0, 0) ) { ... }      # perltidy -pt=2 -kpit=0

In the second case the -pt=2 parameter makes all of the parens tight. In the third case the -kpit=0 flag causes the space within the if parens to have a space, since if is one of the keywords to which the -kpit flag applies by default โœจ. The remaining parens are still tight because of the -pt=2 parameter.

The set of keywords this parameter applies to by default are:

    if elsif unless while until for foreach

These can be changed with the parameter -kpitl=s described in the next section.

  • -kpitl=string, --keyword-paren-inner-tightness-list=string โ€” this command can be used to change the keywords to which the previous parameter, -kpit=n, applies. The parameter string is a required list either keywords or functions, which should be placed in quotes if there are more than one. By itself, this parameter does not cause any change in spacing, so the -kpit=n command is still required ๐Ÿ’–.

For example, the commands "-kpitl="if else while" -kpit=2" will cause just the spaces inside parens following if, else, and while keywords to follow the tightness value indicated by the -kpit=2 flag.

  • -lop, --logical-padding โ€” in the following example some extra space has been inserted on the second line between the two open parens. This extra space is called "logical padding" and is intended to help align similar things vertically in some logical or ternary expressions ๐Ÿฆ‹.
    # perltidy [default formatting]
    $same =
      (      ( $aP eq $bP )
          && ( $aS eq $bS )
          && ( $aT eq $bT )
          && ( $a->{'title'} eq $b->{'title'} )
          && ( $a->{'href'} eq $b->{'href'} ) );

Note that this is considered to be a different operation from "vertical alignment" because space at just one line is being adjusted, whereas in "vertical alignment" the spaces at all lines are being adjusted. So it is sort of a local version of vertical alignment ๐Ÿ‘‘

Here's an example involving a ternary operator:

    # perltidy [default formatting]
    $bits =
        $top > 0xffff ? 32
      : $top > 0xff   ? 16
      : $top > 1      ? 8
      :                 1;

This behavior is controlled with the flag --logical-padding, which is set 'on' by default. If it is not desired it can be turned off using --nological-padding or -nlop. The above two examples become, with -nlop:

    # perltidy -nlop
    $same =
      ( ( $aP eq $bP )
          && ( $aS eq $bS )
          && ( $aT eq $bT )
          && ( $a->{'title'} eq $b->{'title'} )
          && ( $a->{'href'} eq $b->{'href'} ) );

    # perltidy -nlop
    $bits =
      $top > 0xffff ? 32
      : $top > 0xff ? 16
      : $top > 1    ? 8
      :               1;

๐ŸŒธ Trimming whitespace around "qw" quotes ๐ŸŒธ

  • -tqw, --trim-qw โ€” provides the default behavior of trimming spaces around multiline "qw" quotes and indenting them appropriately ๐Ÿ˜Œ.
  • -ntqw, --notrim-qw โ€” cause leading and trailing whitespace around multiline "qw" quotes to be left unchanged. This option will not normally be necessary, but was added for testing purposes, because in some versions of perl, trimming "qw" quotes changes the syntax tree ๐Ÿ‘€.
  • -sbq=n, --space-backslash-quote=n โ€” lines like
    $str1=\"string1";
    $str2=\'string2';

can confuse syntax highlighters unless a space is included between the backslash and the single or double quotation mark ๐Ÿ˜ญ.

This can be controlled with the value of n as follows:

  • -sbq=0 means no space between the backslash and quote
  • -sbq=1 means follow the example of the source code
  • -sbq=2 means always put a space between the backslash and quote

The default is -sbq=1, meaning that a space will be used if there is one in the source code ๐Ÿ’….

๐ŸŽ€ Trimming trailing whitespace from lines of POD ๐ŸŽ€

  • -trp, --trim-pod โ€” will remove trailing whitespace from lines of POD โœจ. The default is not to do this.

๐Ÿ’ฌ Comment Controls ๐Ÿ’ฌ

Perltidy has a number of ways to control the appearance of both block comments and side comments. The term block comment here refers to a full-line comment, whereas side comment will refer to a comment which appears on a line to the right of some code ๐Ÿซถ.

Perltidy does not do any word wrapping of commented text to match a selected maximum line length. This is because there is no way to determine if this is appropriate for the given content. However, an interactive program named perlcomment.pl is available in the examples folder of the perltidy distribution which can assist in doing this ๐Ÿ‘‘

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

The alternative is -nibc:

 # this comment is not indented              (-nibc)
                if ($task) { yyy(); }

See also the next item, -isbc, as well as -sbc, for other ways to have some indented and some outdented block comments ๐Ÿ’–.

  • -isbc, --indent-spaced-block-comments โ€” if there is no leading space on the line, then the comment will not be indented, and otherwise it may be โœจ.

If both -ibc and -isbc are set, then -isbc takes priority.

  • -olc, --outdent-long-comments โ€” when -olc is set, lines which are full-line (block) comments longer than the value maximum-line-length will have their indentation removed. This is the default; use -nolc to prevent outdenting ๐Ÿ˜Œ.
  • -msc=n, --minimum-space-to-comment=n โ€” side comments look best when lined up several spaces to the right of code. Perltidy will try to keep comments at least n spaces to the right. The default is n=4 spaces ๐ŸŒˆ.
  • -fpsc=n, --fixed-position-side-comment=n โ€” this parameter tells perltidy to line up side comments in column number n whenever possible. The default, n=0, will not do this ๐Ÿ’….
  • -iscl, --ignore-side-comment-lengths โ€” this parameter causes perltidy to ignore the length of side comments when setting line breaks. The default, -niscl, is to include the length of side comments when breaking lines to stay within the length prescribed by the -l=n maximum line length parameter. For example, the following long single line would remain intact with -l=80 and -iscl:
    perltidy -l=80 -iscl
       $vmsfile =~ s/;[\d\-]*$//; # Clip off version number; we can use a newer version

whereas without the -iscl flag the line will be broken:

    perltidy -l=80
       $vmsfile =~ s/;[\d\-]*$//
         ;    # Clip off version number; we can use a newer version
  • -ipc, --ignore-perlcritic-comments โ€” perltidy, by default, will look for side comments beginning with ## no critic and ignore their lengths when making line break decisions, even if the user has not set -iscl. The reason is that an unwanted line break can make these special comments ineffective in controlling perlcritic ๐Ÿ‘€.

Setting --ignore-perlcritic-comments tells perltidy not to look for these ## no critic comments.

  • -hsc, --hanging-side-comments โ€” by default, perltidy tries to identify and align "hanging side comments", which are something like this:
        my $IGNORE = 0;    # This is a side comment
                           # This is a hanging side comment
                           # And so is this

A comment is considered to be a hanging side comment if (1) it immediately follows a line with a side comment, or another hanging side comment, and (2) there is some leading whitespace on the line. To deactivate this feature, use -nhsc or --nohanging-side-comments. If block comments are preceded by a blank line, or have no leading whitespace, they will not be mistaken as hanging side comments ๐Ÿฆ‹.

๐Ÿ’œ Closing Side Comments ๐Ÿ’œ

A closing side comment is a special comment which perltidy can automatically create and place after the closing brace of a code block. They can be useful for code maintenance and debugging ๐Ÿ”ฅ. The command -csc (or --closing-side-comments) adds or updates closing side comments. For example, here is a small code snippet

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

And here is the result of processing with perltidy -csc:

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

A closing side comment was added for sub message in this case, but not for the if and else blocks, because they were below the 6 line cutoff limit for adding closing side comments. This limit may be changed with the -csci command, described below ๐Ÿ‘‘.

The command -dcsc (or --delete-closing-side-comments) reverses this process and removes these comments.

Several commands are available to modify the behavior of these two basic commands, -csc and -dcsc:

Alright bestie, we're deep in the formatting options now and it's giving very detailed, but honestly? Iconic of perltidy to be this thorough. Let's get into it. ๐Ÿ’…

  • -csci=n, --closing-side-comment-interval=n โ€” here n is the minimum number of lines a block needs to have before it can get a closing side comment. Default is n=6. Watch this glow up:
# perltidy -csci=2 -csc
sub message {
    if ( !defined( $_[0] ) ) {
        print("Hello, World\n");
    } ## end if ( !defined( $_[0] ))
    else {
        print( $_[0], "\n" );
    } ## end else [ if ( !defined( $_[0] ))
} ## end sub message

Now both the if and the else blocks got commented. But ngl, it's a lot now. Very cluttered, very much "too much going on".

  • -cscp=string, --closing-side-comment-prefix=string โ€” string is the prefix that sits before the block type name. The default prefix, shown above, is "## end". This string gets added to closing side comments, and it's also how perltidy recognizes them when it needs to update, delete, or format them. Any comment flagged as a closing side comment gets placed exactly one single space to the right of its closing brace.
  • -cscl=string, --closing-side-comment-list โ€” string here is a list of block types that should get tagged with closing side comments. By default, every code block type preceded by a keyword or label (like "if", "sub", etc.) gets tagged. The -cscl command swaps that default list out for whatever block types you pick; check "Specifying Block Types" for the deets. Like, this command asks that only "sub"s, labels, "BEGIN", and "END" blocks be touched by operations that add (-csc) or delete (-dcsc) closing side comments:
--closing-side-comment-list='sub : BEGIN END'
  • -cscxl=string, --closing-side-comment-exclusion-list โ€” string is a list of block types that should NOT get tagged with closing side comments. If a block type shows up in both -cscl and -cscxl, then -cscxl wins and the block stays untagged. Periodt.

So for example, this command asks that anonymous subs stay untouched by any -csc or -dcsc operation:

--closing-side-comment-exclusion-list='asub'

By default? No block types are excluded. None. Zero. ๐Ÿซถ

  • -csct=n, --closing-side-comment-maximum-text=n โ€” the text tacked onto certain block types (like an "if" block) is whatever sits between the keyword that opens the block (like "if") and the opening brace. Since that could be way too much for a side comment, there's gotta be a limit, and that's literally what this param is for. Default is n=20, meaning no extra tokens get appended once that text hits 20 characters. Anything left out gets marked with "...". (Tokens, including sub names, never get truncated tho, so the real length can still go over). For example: in the code above, the appended text of the first block is " ( !defined( $_[0] )...". The n=20 limit is what caused that truncation, hence the "...". Peep the next flag for more control over the abbreviated text.
  • -cscb, --closing-side-comments-balanced โ€” okay so like we just said, once you blow past the closing-side-comment-maximum-text limit, the comment text has to get truncated. Older perltidy versions ended it with three dots, and you can still do that with -ncscb:
perltidy -csc -ncscb
} ## end foreach my $foo (sort { $b cmp $a ...

But that's a problem for editors that can't recognize comments or aren't set up to, because they can't "bounce" around the text properly. So -cscb was added to help them out by appending the right balancing structure:

perltidy -csc -cscb
} ## end foreach my $foo (sort { $b cmp $a ... })

Default is -cscb. Slay.

  • -csce=n, --closing-side-comment-else-flag=n โ€” the default, n=0, drops the text of the opening "if" statement after any terminal "else".

If you use n=2, then every "elsif" also gets the text of the opening "if" statement. And an "else" will include the text of a preceding "elsif" statement. Heads up: this can make some long closing side comments. ๐Ÿ˜ญ

If you use n=1, the results match n=2 whenever the resulting line length stays under the max allowed.

  • -cscb, --closing-side-comments-balanced โ€” (yes, it's showing up again, bestie, stay with me). When you're using closing-side-comments and you blow past the closing-side-comment-maximum-text limit, the comment text has to get abbreviated. It gets ended with three dots if the -cscb flag is negated:
perltidy -csc -ncscb
} ## end foreach my $foo (sort { $b cmp $a ...

This is a problem for older editors that don't recognize comments, because they can't "bounce" around the text right. The -cscb flag tries to help them by appending appropriate terminal balancing structures:

perltidy -csc -cscb
} ## end foreach my $foo (sort { $b cmp $a ... })

Default is -cscb. (Same answer as before, because it's the same flag โ€” perltidy said it twice, we're saying it twice.)

  • -cscw, --closing-side-comment-warnings โ€” this param is here to help you survive the transition into using closing side comments. It makes two things happen if a closing side comment replaces an existing different closing side comment: first, you get an error message, and second, the original side comment gets plopped alone on a new specially marked comment line for later attention.

The whole point is to avoid clobbering hand-written side comments that just happen to match the closing side comment pattern. This flag should only be needed on your first run with -csc.


๐Ÿšจ Important Notes on Closing Side Comments ๐Ÿšจ

  • Closing side comments only get placed on lines terminated with a closing brace. Certain closing styles, like cuddled elses (-ce), actually prevent some closing side comments from being generated at all.
  • Please note: adding or deleting closing side comments happens only through -csc or -dcsc. Every other command, if used, just modifies how those two behave.
  • It's recommended you use the -cscw flag alongside -csc on the first perltidy run on any given file. This prevents losing existing side comment data that happens to have the csc prefix.
  • Once you use -csc, keep using it so your closing side comments stay correct as the code changes. Otherwise they'll go stale and wrong once the code updates.
  • If you edit the closing side comments perltidy generated, you MUST also change the prefix so it's different from the closing side comment prefix. Otherwise your edits get yeeted when you rerun perltidy with -csc. For example, just change "## end" to "## End", since the test is case sensitive. You might also want the -ssc flag to keep those modified closing side comments spaced the same as actual closing side comments.
  • Temporarily generating closing side comments is a super useful trick for exploring and/or debugging a perl script, especially one somebody else wrote. And you can always remove them with -dcsc. No cap, this is lowkey the move. ๐Ÿ’–

๐ŸŒธ Static Block Comments ๐ŸŒธ

Static block comments are block comments with a special leading pattern โ€” "##" by default โ€” that get treated a little differently from other block comments. They basically act like they've got glue on their left and top edges, because they stick to the left edge and the previous line whenever there's no blank space in those spots. This option is especially useful for controlling how commented code gets displayed.

-sbc, --static-block-comments

When -sbc is used, a block comment with a special leading pattern โ€” "##" by default โ€” gets treated specially.

Comments identified this way are handled like so:

  • If there's no leading space on the line, the comment won't get indented (otherwise it might be),
  • no new blank line gets inserted before such a comment, and
  • such a comment will never become a hanging side comment.

For example, assuming @month_of_year is left-adjusted:

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

Without this convention, that code would become this instead:

@month_of_year = (   # -nsbc
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',

    ##  'Dec', 'Nov'
    'Nov', 'Dec'
);

which is not as clear, honestly. Default is to use -sbc. You can turn it off with -nsbc.

-sbcp=string, --static-block-comment-prefix=string

This parameter defines the prefix used to identify static block comments when -sbc is set. The default prefix is "##", matching -sbcp=##. The prefix is actually part of a perl pattern used to match lines, and it has to start with either "#" or "^#". In the first case, a prefix ^\s* gets added to match any leading whitespace; in the second case, the pattern only matches comments with no leading whitespace. Like, to identify all comments as static block comments, you'd use -sbcp=#. To identify all left-adjusted comments as static block comments, use -sbcp='^#'.

Please note that -sbcp only defines the pattern for identifying static block comments โ€” it won't be used at all unless the -sbc switch is set. Also, be aware that since this string goes into a perl regular expression that identifies these comments, it has to allow a valid regular expression to be formed.

A pattern that can be useful is:

okay so -sbcp=^#{2,}[^\s#] โ€” this pattern is the vibe check for static block comments ๐Ÿ’… It says a static block comment has to contain at least one character that is neither a # nor a space. Why do we even care? Because it lets a line that's literally just #s get rejected as a static block comment ๐Ÿšซ โ€” and those all-# lines love to pop up at the start and end of header info in subroutines. They should not get separated from the comments in between, which typically start with just a single #. iykyk

  • -osbc, --outdent-static-block-comments โ€” this one makes static block comments outdent by however many --continuation-spaces=n you set, if possible. โœจ

๐ŸŒธ Static Side Comments ๐ŸŒธ

So static side comments are just side comments with a special leading pattern. This option is lowkey a lifesaver for controlling how commented code shows up when it's sitting there as a side comment. ๐Ÿ’–

  • -ssc, --static-side-comments โ€” when you use -ssc, a side comment with a static leading pattern (which is ## by default) gets spaced only a single space from the previous character, and it will not be vertically aligned with the other side comments. No lining up, no matching, she's doing her own thing ๐Ÿฆ‹ The default is -nssc โ€” so off unless you say otherwise.
  • -sscp=string, --static-side-comment-prefix=string โ€” this parameter is the one that defines the prefix used to identify static side comments when the -ssc parameter is set. Default prefix is "##", which corresponds to "-sscp=##". ๐Ÿ‘‘
bestie, listen: -sscp merely defines the pattern used to identify static side comments. It will not be used unless the switch -ssc is set. ๐Ÿซถ

Also โ€” and this matters โ€” this string gets used inside a perl regular expression which identifies these comments, so it must enable a valid regular expression to be formed. No chaos allowed. ๐Ÿ˜ญ

โœจ Skipping Selected Sections of Code โœจ

So you can pass selected lines of code through verbatim to the output with zero formatting โ€” all you gotta do is mark the starting and ending lines with special comments. There are two options for this: the first is called --format-skipping (aka -fs), and the second is called --code-skipping (aka -cs). ๐ŸŒˆ

In both cases the lines of code get output without any changes, periodt. The difference is: with --format-skipping, perltidy will still parse the marked lines of code and check for errors ๐Ÿ‘€, whereas with --code-skipping, perltidy just passes the lines straight to the output with no checking whatsoever. ๐Ÿ’€

Both of these features are enabled by default and get invoked with special comment markers. --format-skipping uses the starting and ending markers '#<<<' and '#>>>', like this:

#<<<  format skipping: do not let perltidy change my nice formatting
   my @list = (1,
               1, 1,
               1, 2, 1,
               1, 3, 3, 1,
               1, 4, 6, 4, 1,);
#>>>

--code-skipping uses starting and ending markers '#<<V' and '#>>V', like this:

#<<V  code skipping: perltidy passes this verbatim, no error checking

   token ident_digit {
       [ [ <?word> | _ | <?digit> ] <?ident_digit>
       |   <''>
       ]
   };

#>>V

(That last character V is like a < or > rotated 90 degrees, in case you were wondering ๐ŸŒ€). Additional text may appear on the special comment lines, as long as it's separated from the marker by at least one space to highlight the sign โ€” exactly like in the examples above.

Any number of code-skipping or format-skipping sections may appear in a file. And here's the tea: if an opening code-skipping or format-skipping comment is not followed by a corresponding closing comment, then the skipping continues to the end of the file. ๐Ÿ˜ณ On the flip side, if a closing code-skipping or format-skipping comment appears in a file but doesn't follow a corresponding opening comment, then it's just treated as an ordinary comment with no special meaning. Fake marker, no power. ๐Ÿ™ˆ

Recommendation time ๐Ÿ’… it is recommended to use --code-skipping only if you need to hide a block of an extended syntax which would produce errors if parsed by perltidy, and to use --format-skipping otherwise. Why? Because --format-skipping gives you the benefits of error checking, and there are essentially no limitations on which lines it can be applied to. The --code-skipping option, on the other hand, does not do error checking, and its use is more restrictive โ€” because the code that remains, after skipping the marked lines, must be syntactically correct code with balanced containers. ๐Ÿงš

These features should be used sparingly to avoid littering your code with markers, but they can be genuinely helpful for working around occasional problems. ๐ŸŒŸ

Also note: it may be possible to avoid using --format-skipping for the specific case of a comma-separated list of values (like in the example above) by simply inserting a blank or comment somewhere between the opening and closing parens. See the section "Controlling List Formatting". ๐ŸŽ€

The following sections describe the available controls for these options. They should not normally be needed. ๐Ÿ‘‘


  • -fs, --format-skipping โ€” as explained above, this flag (enabled by default) causes any code between special beginning and ending comment markers to be passed to the output without formatting. But โ€” and this is the whole point โ€” the code between the comments is still checked for errors. โœ… The default beginning marker is #<<< and the default ending marker is #>>>.

Format skipping begins when a format skipping beginning comment is seen and continues until a format-skipping ending comment is found.

This feature can be disabled with -nfs. This should not normally be necessary. ๐Ÿ™…

  • -fsb=string, --format-skipping-begin=string โ€” this and the next parameter let you change the special beginning and ending comments. But fr, it's recommended that they only be changed if there's a conflict between the default values and some other use. And if you do use them, it's recommended they only be entered in a .perltidyrc file rather than on a command line โ€” because properly escaping these parameters on a command line can be difficult. ๐Ÿ˜ญ

If changed comment markers don't appear to be working, use the -log flag and examine the .LOG file to see if and where they're being detected. ๐Ÿ”

The -fsb=string parameter may be used to change the beginning marker for format skipping. The default is equivalent to -fsb='#<<<'. The string you enter must begin with a # and should be in quotes as necessary to get past the command shell of your system. It is actually the leading text of a pattern that's constructed by appending a '\s', so you must also include backslashes for characters to be taken literally rather than as patterns. ๐Ÿ’…

Some examples showing how example strings become patterns:

-fsb='#\{\{\{' becomes /^#\{\{\{\s/ which matches #{{{ but not #{{{{
-fsb='#\*\*'   becomes /^#\*\*\s/   which matches #** but not #***
-fsb='#\*{2,}' becomes /^#\*{2,}\s/ which matches #** and #*****
  • -fse=string, --format-skipping-end=string โ€” the -fse=string is the corresponding parameter used to change the ending marker for format skipping. The default is equivalent to -fse='#<<<'. ๐Ÿคจ

The beginning and ending strings may be the same, but it's preferable to make them different for clarity. (Yes really, that's what it says โ€” make of it what you will ๐ŸŒธ)

  • -cs, --code-skipping โ€” as explained above, this flag (enabled by default) causes any code between special beginning and ending comment markers to be directly passed to the output with no error checking and no formatting. Essentially, perltidy treats it as if it were a block of arbitrary text. ๐Ÿ’€ The default beginning marker is #<<V and the default ending marker is #>>V.

This feature can be disabled with -ncs. This should not normally be necessary. ๐Ÿ™…

  • -csb=string, --code-skipping-begin=string โ€” this may be used to change the beginning comment for a --code-skipping section, and its use is similar to the -fsb=string. The default is equivalent to -csb='#<<V'.
  • -cse=string, --code-skipping-end=string โ€” this may be used to change the ending comment for a --code-skipping section, and its use is similar to the -fse=string. The default is equivalent to -cse='#>>V'.

๐Ÿฆ‹ Formatting a Limited Range of Lines ๐Ÿฆ‹

There's a command --line-range-tidy=n1:n2 that's available to process just a selected range of lines of an input stream with perltidy. This command is mainly of interest for programming interactive code editors. ๐Ÿ‘ฉโ€๐Ÿ’ป When it's used, the entire input stream is read, but just the selected range of lines of the input file are processed by the perltidy tokenizer and formatter, and then the stream is reassembled for output. The selected lines need to contain a complete statement or balanced container โ€” otherwise, a syntax error will occur and the code will not be tidied. ๐Ÿ˜ญ

There are a couple of limitations on the use of this command: (1) it may not be applied to multiple files, and (2) it only applies to code tidying and not, for example, html formatting. โœจ

  • -lrt=n1:n2, --line-range-tidy=n1:n2 โ€” the range of lines is specified by integers n1 and n2, where n1 is the first line number to be formatted (start counting with 1 ๐Ÿ’…) and n2 is the last line number to be formatted. If n2 is not given, or exceeds the actual number of lines, then formatting continues to the end of the file. ๐ŸŒˆ

Examples:

--line-range-tidy=43:109      # tidy lines 43 through 109
--line-range-tidy=' 43 : 109' # tidy lines 43 through 109
--line-range-tidy=1:          # tidy all lines
--line-range-tidy=0:90        # ERROR (n1 must be >= 1)

The second example shows that spaces are okay if placed in quotes. ๐Ÿซถ

๐Ÿ‘‘ Line Break Control ๐Ÿ‘‘

The parameters in this and the next sections control breaks after non-blank lines of code. Blank lines are controlled separately by parameters in the section <italic>"Blank Line Control"*. ๐Ÿงš

  • -dnl, --delete-old-newlines โ€” by default, perltidy first deletes all old line break locations, and then it goes looking for good break points to match the desired line length. Use -ndnl or --nodelete-old-newlines to force perltidy to retain all old line break points. ๐Ÿ“Œ
  • -anl, --add-newlines โ€” by default, perltidy will add line breaks when necessary to create continuations of long lines and to improve the script appearance. Use -nanl or --noadd-newlines to prevent any new line breaks. ๐Ÿšซ

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

  • -fnl, --freeze-newlines โ€” bestie, if you literally do not want a single line break inside your code lines to be touched, set -fnl and they stay frozen, periodt. Everything else in this section, plus the stuff in "Controlling List Formatting" and "Retaining or Ignoring Existing Line Breaks", is just gonna sit there vibing. You might wanna pair this with --nooutdent-long-lines โœจ
Note: if you also want your blank lines kept exactly as-is, hit up --freeze-blank-lines, which lives in the "Blank Line Control" section ๐Ÿ‘‘

โœจ Controlling Breaks at Braces, Parens, and Square Brackets โœจ

  • -ce, --cuddled-else โ€” turns on the "cuddled else" style, where else and elsif slide right up after the closing curly brace of the previous block, no cap ๐Ÿซถ. Default is to not cuddle, which is what -nce / --nocuddled-else means. Here's the side-by-side comparison so you can see it:
# -ce
if ($task) {
    yyy();
} else {
    zzz();
}

# -nce (default)
if ($task) {
    yyy();
}
else {
    zzz();
}

In that example, the keyword else sits on the same line that starts with the previous closing block brace, and its own opening block brace follows on that same line. Other keywords and function names that get this "cuddled" treatment are elsif, continue, catch, and finally ๐Ÿ’….

Other block types can get the cuddle treatment by naming them on a separate parameter, --cuddled-block-list, which we get to in a later section.

Cuddling two code blocks together requires that the closing brace of the first block start a new line. If that block is entirely on one line in your input file, somebody's gotta decide whether to break it open so cuddling can happen. That decision is controlled by --cuddled-break-options=n (-cbo=n), discussed below. The default and recommended value, -cbo=1, bases the decision on the first block in the chain: if it spans multiple lines, then cuddling happens and keeps going down the chain, no matter how big or small the later blocks are. Otherwise, short lines stay intact ๐Ÿฆ‹.

So for example, --cuddled-else would have zero effect if the snippet above is rewritten as:

if ($task) { yyy() }
else {    zzz() }

If the first block spans multiple lines, cuddling can happen and will continue for the rest of the blocks in the chain, like the previous snippet showed.

Blank lines between cuddled blocks? Eliminated. Comments after the closing brace where cuddling would occur? Cuddling gets prevented ๐Ÿ˜ญ. But if that happens, cuddling will restart later in the chain if it can.

  • -cb, --cuddled-blocks โ€” this flag is exactly equivalent to --cuddled-else (-ce).
  • -cbl, --cuddled-block-list โ€” the built-in default cuddled block types are else, elsif, continue, catch, finally.

You can define extra block types for the --cuddled-blocks style to apply to with this parameter. It's a character string: a list of block types separated by commas or spaces. So like, to cuddle sort, map, and grep blocks in addition to the defaults, you'd set the string to

-cbl="sort map grep"

or equivalently

-cbl=sort,map,grep

Heads up though โ€” those particular block types are usually pretty short, so there might not be much opportunity for the cuddled style to shine ๐Ÿ™ˆ.

Using commas means you don't have to protect spaces with quotes. Slay.

As a diagnostic check, --dump-cuddled-block-list or -dcbl lets you view the hash of values generated by this flag ๐Ÿ‘€.

Finally: the --cuddled-block-list parameter by itself just specifies which blocks get the cuddled format. It does absolutely nothing unless you activate the style with --cuddled-else.

  • -cblx, --cuddled-block-list-exclusive โ€” when cuddled else formatting is on via --cuddled-else, setting this flag makes perltidy straight-up ignore its built-in defaults and rely exclusively on the block types you specified in --cuddled-block-list from the previous section. For example, to avoid cuddled catch and finally (both defaults), you could use:
perltidy -ce -cbl='else elsif continue' -cblx
  • -cbo=n, --cuddled-break-option=n โ€” cuddled formatting is only possible between a pair of code blocks if the closing brace of the first block starts a new line. So if perltidy runs into a block that's entirely on a single line, and cuddled formatting is selected, it has to decide whether to "break" the block โ€” meaning make it span multiple lines. This parameter controls that decision. The options:
cbo=0  Never force a short block to break.
cbo=1  If the first of a pair of blocks is broken in the input
       file, then break the second [DEFAULT].
cbo=2  Break open all blocks for maximal cuddled formatting.

The default and recommended value is cbo=1. With that, if the starting block of a chain spans multiple lines, a whole cascade of breaks happens for the remaining blocks, cuddling the entire chain together ๐Ÿ”ฅ.

The option cbo=0 can produce erratic cuddling if you've got a bunch of one-line blocks lying around.

The option cbo=2 produces maximal cuddling, but it will not allow any short blocks. No exceptions.

  • -bl, --opening-brace-on-new-line, or --brace-left โ€” use -bl to put an opening block brace on a new line:
if ( $input_file eq '-' )
{
    ...
}

By default it applies to all structural blocks except sort, map, grep, eval, and anonymous subs.

The default is -nbl, which puts an opening brace on the same line as the keyword introducing it, if possible. Like so:

# default
if ( $input_file eq '-' ) {
   ...
}

When -bl is set, you can control which blocks it applies to with --brace-left-list and --brace-left-exclusion-list, described in the next sections ๐Ÿ’–.

  • -bll=s, --brace-left-list=s โ€” use this to change which types of block braces the -bl flag applies to; see "Specifying Block Types". So like -bll='if elsif else sub' would apply it only to if/elsif/else and named sub blocks. The default is all blocks: -bll='*' โœจ.
  • -blxl=s, --brace-left-exclusion-list=s โ€” use this to exclude types of block braces from the -bl flag; see "Specifying Block Types" again. For example, the default settings -bll='*' and -blxl='sort map grep eval asub' mean all blocks except sort, map, grep, eval, and anonymous sub blocks.

Note that -bll=s and -blxl=s control the behavior of -bl but do absolutely nothing unless -bl is set. These two lists give you complete control over this flag, but there are also two shortcut flags available, described in the next sections ๐ŸŽ€.

  • -sbl, --opening-sub-brace-on-new-line โ€” the -sbl flag is a shortcut to turn on -bl just for named subs. You could get the same effect by turning on -bl with the block list set to -bll='sub'. To avoid conflicts, it's recommended to pick either the more general list method above or this shortcut method โ€” not both, bestie.

For example,

perltidy -sbl

produces this result:

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

The negative version, -nsbl, turns off -bl for named subs. Same thing can be done with the exclusion list method, -blxl=sub ๐Ÿ’œ.

  • -asbl, --opening-anonymous-sub-brace-on-new-line โ€” -asbl is like -sbl except it applies to anonymous subs instead of named subs. Same effect achievable by turning on -bl with the block list set to include -bll='asub'.

For example

perltidy -asbl

produces this result:

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

The negative version, -nasbl, turns off -bl for anonymous subs ๐ŸŒธ.

  • -bli, --brace-left-and-indent โ€” -bli is similar to -bl but it also drops one unit of continuation indentation (see --continuation-indentation) before an opening and closing block brace.

For example

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

By default, this extra indentation happens for block types: if, elsif, else, unless, while, for, foreach, do, plus named subs and blocks preceded by a label. The next item shows how to change that ๐Ÿฆ‹.

Note: -bli is similar to -bl, except the braces get indented. But these two flags are implemented independently and have different default settings for historical reasons. If you want a mixture of effects, you can turn both on with different -list settings. And if both settings get selected for a certain block type, the -bli style wins. Priority, periodt ๐Ÿ‘‘.
  • -blil=s, --brace-left-and-indent-list=s โ€” use this to change which types of block braces the -bli flag applies to; see "Specifying Block Types".

The default is -blil='if else elsif unless while for foreach do : sub'.

  • -blixl=s, --brace-left-and-indent-exclusion-list=s โ€” use this to exclude types of block braces from the -bli flag; see "Specifying Block Types".

This might be useful alongside selecting all blocks with -blil='*'. The default setting is -blixl=' ', which excludes nothing ๐Ÿ™ˆ.

Note that -blil and -blixl control the behavior of the -bli flag but do nothing at all unless -bli is set โœจ.

  • -bar, --opening-brace-always-on-right โ€” bestie, this is about where the opening curly goes. The default style, -nbl, puts the opening code block brace on a new line if it doesn't fit on the same line as the opening keyword, like this:
if ( $bigwasteofspace1 && $bigwasteofspace2
  || $bigwasteofspace3 && $bigwasteofspace4 )
{
    big_waste_of_time();
}

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

if ( $bigwasteofspace1 && $bigwasteofspace2
  || $bigwasteofspace3 && $bigwasteofspace4 ) {
    big_waste_of_time();
}
A conflict occurs if both --opening-brace-on_new_line (-bl) and -bar are specified. ๐Ÿ’€ pick one, babe.
  • -cpb, --cuddled-paren-brace โ€” a related parameter, --cuddled-paren-brace, makes perltidy join two lines which otherwise would be
  )
{

to be

) {

For example:

# default
foreach my $dir (
    '05_lexer', '07_token', '08_regression', '11_util',
    '13_data',  '15_transform'
  )
{
    ...
}

# perltidy -cpb
foreach my $dir (
    '05_lexer', '07_token', '08_regression', '11_util',
    '13_data',  '15_transform'
) {
    ...;
}
  • -otr, --opening-token-right and related flags โ€” the -otr flag is a hint that perltidy should not place a break between a comma and an opening token. So like:
# default formatting
push @{ $self->{$module}{$key} },
  {
    accno       => $ref->{accno},
    description => $ref->{description}
  };

# perltidy -otr
push @{ $self->{$module}{$key} }, {
    accno       => $ref->{accno},
    description => $ref->{description}
  };

The flag -otr is actually an abbreviation for three other flags โœจ which can be used to control parens, hash braces, and square brackets separately if desired:

  • -opr or --opening-paren-right
  • -ohbr or --opening-hash-brace-right
  • -osbr or --opening-square-bracket-right
  • -bbhb=n, --break-before-hash-brace=n and related flags โ€” when a list of items spans multiple lines, the default formatting places the opening brace (or other container token) at the end of the starting line, like this:
$romanNumerals = {
    one   => 'I',
    two   => 'II',
    three => 'III',
    four  => 'IV',
};

This flag can change the default behavior to cause a line break to be placed before the opening brace according to the value given to the integer n:

  • -bbhb=0 never break [default]
  • -bbhb=1 stable: break if the input script had a break
  • -bbhb=2 break if list is 'complex' (see note below)
  • -bbhb=3 always break

For example,

# perltidy -bbhb=3
$romanNumerals =
  {
    one   => 'I',
    two   => 'II',
    three => 'III',
    four  => 'IV',
  };

There are several points to note about this flag ๐Ÿ‘€:

  • This parameter only applies if the opening brace is preceded by an '=' or '=>'.
  • This parameter only applies if the contents of the container looks like a list. The contents need to contain some commas or '=>'s at the next interior level to be considered a list.
  • For the n=2 option, a list is considered 'complex' if it is part of a nested list structure which spans multiple lines in the input file.
  • If multiple opening tokens have been 'welded' together with the -wn parameter, then this parameter has no effect.
  • The indentation of the braces will normally be one level of continuation indentation by default. This can be changed with the parameter -bbhbi=n in the next section.
  • Similar flags for controlling parens and square brackets are given in the subsequent section.
  • -bbhbi=n, --break-before-hash-brace-and-indent=n โ€” this flag is a companion to -bbhb=n for controlling the indentation of an opening hash brace which is placed on a new line by that parameter ๐Ÿ’…. The indentation is as follows:
    • -bbhbi=0 one continuation level [default]
    • -bbhbi=1 outdent by one continuation level
    • -bbhbi=2 indent one full indentation level

For example:

# perltidy -bbhb=3 -bbhbi=1
$romanNumerals =
{
    one   => 'I',
    two   => 'II',
    three => 'III',
    four  => 'IV',
};

# perltidy -bbhb=3 -bbhbi=2
$romanNumerals =
    {
    one   => 'I',
    two   => 'II',
    three => 'III',
    four  => 'IV',
    };
Note that this parameter has no effect unless -bbhb=n is also set. no cap.
  • -bbsb=n, --break-before-square-bracket=n โ€” this flag is similar to the flag described above, except it applies to lists contained within square brackets:
    • -bbsb=0 never break [default]
    • -bbsb=1 stable: break if the input script had a break
    • -bbsb=2 break if list is 'complex' (part of nested list structure)
    • -bbsb=3 always break
  • -bbsbi=n, --break-before-square-bracket-and-indent=n โ€” this flag is a companion to -bbsb=n for controlling the indentation of an opening square bracket which is placed on a new line by that parameter ๐ŸŽ€. The indentation is as follows:
    • -bbsbi=0 one continuation level [default]
    • -bbsbi=1 outdent by one continuation level
    • -bbsbi=2 indent one full indentation level
  • -bbp=n, --break-before-paren=n โ€” this flag is similar to -bbhb=n, described above, except it applies to lists contained within parens:
    • -bbp=0 never break [default]
    • -bbp=1 stable: break if the input script had a break
    • -bpb=2 break if list is 'complex' (part of nested list structure)
    • -bbp=3 always break
  • -bbpi=n, --break-before-paren-and-indent=n โ€” this flag is a companion to -bbp=n for controlling the indentation of an opening paren which is placed on a new line by that parameter ๐ŸŒธ. The indentation is as follows:
    • -bbpi=0 one continuation level [default]
    • -bbpi=1 outdent by one continuation level
    • -bbpi=2 indent one full indentation level
  • -bfvt=n, --brace-follower-vertical-tightness=n โ€” some types of closing block braces, such as eval, may be followed by additional code. A line break may be inserted between such a closing brace and the following code depending on the parameter n and the length of the trailing code, as follows:

If the trailing code fits on a single line, then

  • -bfvt=0 Follow the input style regarding break/no-break
  • -bfvt=1 Follow the input style regarding break/no-break [Default]
  • -bfvt=2 Do not insert a line break

If the trailing code requires multiple lines, then

  • -bfvt=0 Insert a line break
  • -bfvt=1 Insert a line break except for a cuddled block chain
  • -bfvt=2 Do not insert a line break

The default is -bfvt=1. The most compact code is achieved with -bfvt=2 โœจ.

Example (non-cuddled, multiple lines ):

# -bfvt=0 or -bvft=1 [DEFAULT]
eval {
    ( $line, $cond ) = $self->_normalize_if_elif($line);
    1;
}
  or die sprintf "Error at line %d\nLine %d: %s\n%s",
  ( $line_info->start_line_num() ) x 2, $line, $@;

# -bfvt=2
eval {
    ( $line, $cond ) = $self->_normalize_if_elif($line);
    1;
} or die sprintf "Error at line %d\nLine %d: %s\n%s",
  ( $line_info->start_line_num() ) x 2, $line, $@;

Example (cuddled, multiple lines):

# -bfvt=0
eval {
    #STUFF;
    1;    # return true
}
  or do {
    ##handle error
  };

# -bfvt=1 [DEFAULT] or -bfvt=2
eval {
    #STUFF;
    1;    # return true
} or do {
    ##handle error
};

Welding ๐Ÿฆ‹

  • -wn, --weld-nested-containers โ€” the -wn flag causes closely nested pairs of opening and closing container symbols (curly braces, brackets, or parens) to be "welded" together ๐Ÿ”ฅ, meaning that they are treated as if combined into a single unit, with the indentation of the innermost code reduced to be as if there were just a single container symbol.

For example:

# default formatting
do {
    {
        next if $x == $y;
    }
} until $x++ > $z;

# perltidy -wn
do { {
    next if $x == $y;
} } until $x++ > $z;

When this flag is set perltidy makes a preliminary pass through the file and identifies all nested pairs of containers. To qualify as a nested pair, the closing container symbols must be immediately adjacent and the opening symbols must either (1) be adjacent as in the above example, or (2) have an anonymous sub declaration following an outer opening container symbol which is not a code block brace, or (3) have an outer opening paren separated from the inner opening symbol by any single non-container symbol or something that looks like a function evaluation, as illustrated in the next examples. An additional option (4) which can be turned on with the flag --weld-fat-comma is when the opening container symbols are separated by a hash key and fat comma (=>).

Any container symbol may serve as both the inner container of one pair and as the outer container of an adjacent pair ๐Ÿ‘‘. Consequently, any number of adjacent opening or closing symbols may join together in weld. For example, here are three levels of wrapped function calls:

# default formatting
my (@date_time) = Localtime(
    Date_to_Time(
        Add_Delta_DHMS(
            $year, $month,  $day, $hour, $minute, $second,
            '0',   $offset, '0',  '0'
        )
    )
);
# perltidy -wn
my (@date_time) = Localtime( Date_to_Time( Add_Delta_DHMS(
    $year, $month,  $day, $hour, $minute, $second,
    '0',   $offset, '0',  '0'
) ) );

bestie look at this โ€” the inner lines get their indentation reduced by two whole levels here. And this example is showing you the classic result of this formatting, which is literally a sandwich ๐Ÿฅช: an initial opening layer, a central section of any complexity forming the "meat" of the sandwich, and a final closing layer. This predictable structure is what keeps the compacted thing readable, periodt.

The inner sandwich layer is required to be at least one line thick. If that can't happen, welding does not occur. Heads up tho: this constraint can make formatting take a couple of iterations to stabilize when you first apply it to a script. The --converge flag can be used to insure that the final format is achieved in a single run. ๐Ÿ’…

And here's an example of a welded container within a welded container (containers all the way down, iconic):

# default formatting
$x->badd(
    bmul(
        $class->new(
            abs(
                $sx * int( $xr->num() ) & $sy * int( $yr->num() )
            )
        ),
        $m
    )
);

# perltidy -wn
$x->badd( bmul(
    $class->new( abs(
        $sx * int( $xr->num() ) & $sy * int( $yr->num() )
    ) ),
    $m
) );

The welded closing tokens are by default on a separate line, but you can modify that with the --vertical-tightness-closing=n (-vtc=n) flag (described in the next section ๐Ÿ‘€). Like, same example but adding -vtc=2 gives you:

# perltidy -wn -vtc=2
$x->badd( bmul(
    $class->new( abs(
        $sx * int( $xr->num() ) & $sy * int( $yr->num() ) ) ),
    $m ) );

This format option is quite general but there are some limitations. ngl.

One limitation is that any line length limit still applies and can cause long welded sections to be broken into multiple lines. ๐Ÿ˜ญ

Also, the stacking of containers defined by this flag have priority over any other container stacking flags. This is because any welding is done first.

  • -wfc, --weld-fat-comma โ€” when the -wfc flag is set, along with -wn (--weld-nested-containers), perltidy is allowed to weld an opening paren to an inner opening container when they are separated by a hash key and fat comma (=>). for example
# perltidy -wn -wfc
elf->call_method( method_name_foo => {
    some_arg1       => $foo,
    some_other_arg3 => $bar->{'baz'},
} );

This option is off by default.

  • -wnxl=s, --weld-nested-exclusion-list โ€” the -wnxl=s flag gives you some control over the types of containers which can be welded. The -wn flag by default is "greedy" in welding adjacent containers. If it welds more types of containers than you wanted, this flag is your bestie: it gives you a way to reduce the amount of welding by specifying a list of things which should not be welded. ๐Ÿ›‘

The logic in perltidy to apply this is straightforward. As each container token is being considered for joining a weld, any exclusion rules are consulted and used to reject the weld if necessary.

This list is a string with space-separated items. Each item consists of up to three pieces of information: (1) an optional position, (2) an optional preceding type, and (3) a container type.

The only required piece of information is a container type, which is one of '(', '[', '{' or 'q'. The first three of these are container tokens and the last represents a quoted list. For example the string

-wnxl='[ { q'

means do NOT include square-brackets, braces, or quotes in any welds. The only unspecified container is '(', so this string means that only welds involving parens will be made.

To illustrate, following welded snippet consists of a chain of three welded containers with types '(' '[' and 'q':

# perltidy -wn
skip_symbols( [ qw(
    Perl_dump_fds
    Perl_ErrorNo
    Perl_GetVars
    PL_sys_intern
) ] );

Even though the qw term uses parens as the quote delimiter, it has a special type 'q' here. If it appears in a weld it always appears at the end of the welded chain. ๐ŸŽ€

Any of the container types '[', '{', and '(' may be prefixed with a position indicator which is either '^', to indicate the first token of a welded sequence, or '.', to indicate an interior token of a welded sequence. (Since a quoted string 'q' always ends a chain it does need a position indicator).

For example, if we do not want a sequence of welded containers to start with a square bracket we could use

-wnxl='^['

In the above snippet, there is a square bracket but it does not start the chain, so the formatting would be unchanged if it were formatted with this restriction.

A third optional item of information which can be given is an alphanumeric letter which is used to limit the selection further depending on the type of token immediately before the container. If given, it goes just before the container symbol. The possible letters are currently 'k', 'K', 'f', 'F', 'w', and 'W', with these meanings:

  • 'k' matches if the previous nonblank token is a perl keyword (such as 'if', 'while'),
  • 'K' matches if 'k' does not: previous token is not a keyword
  • 'f' matches if previous token is a function (not a keyword)
  • 'F' matches if 'f' does not
  • 'w' matches if either 'k' or 'f' match
  • 'W' matches if 'w' does not

For example, compare

# perltidy -wn
if ( defined( $_Cgi_Query{
    $Config{'methods'}{'auth'}{'remote'}{'cgi'}{'username'}
} ) )

with

# perltidy -wn -wnxl='^K( {'
if ( defined(
    $_Cgi_Query{ $Config{'methods'}{'auth'}{'remote'}{'cgi'}
          {'username'} }
) )

The first case does maximum welding. In the second case the leading paren is retained by the rule (it would have been rejected if preceded by a non-keyword) but the curly brace is rejected by the rule.

Here are some additional example strings and their meanings:

'^('   - the weld must not start with a paren
'.('   - second and later tokens may not be parens
'.w('  - second and later tokens may not be a keyword or call parens
'('    - no parens in a weld
'^K('  - exclude a leading paren preceded by a non-keyword
'.k('  - exclude a secondary paren preceded by a keyword
'[ {'  - exclude all brackets and braces
'[ ( ^K{' - exclude all except nested structures like do {{  ... }}

โœจ Vertical tightness of non-block curly braces, parentheses, and square brackets. โœจ

These parameters control what shall be called vertical tightness. Here are the main points:

  • Opening tokens (except for block braces) are controlled by -vt=n, or --vertical-tightness=n, where
    • -vt=0 always break a line after opening token (default).
    • -vt=1 do not break unless this would produce more than one step in indentation in a line.
    • -vt=2 never break a line after opening token
  • You must also use the -lp (--line-up-parentheses) flag when you use the -vt flag; the reason is explained below.
  • Closing tokens (except for block braces) are controlled by -vtc=n, or --vertical-tightness-closing=n, where
    • -vtc=0 always break a line before a closing token (default),
    • -vtc=1 do not break before a closing token which is followed by a semicolon or another closing token, and is not in a list environment.
    • -vtc=2 never break before a closing token.
    • -vtc=3 Like -vtc=1 except always break before a closing token if the corresponding opening token follows an = or =>.

The rules for -vtc=1 and -vtc=3 are designed to maintain a reasonable balance between tightness and readability in complex lists.

  • Different controls may be applied to different token types, and it is also possible to control block braces; see below.
  • Finally, please note that these vertical tightness flags are merely hints to the formatter, and it cannot always follow them. Things which make it difficult or impossible include comments, blank lines, blocks of code within a list, and possibly the lack of the --line-up-parentheses parameter. Also, these flags may be ignored for very small lists (2 or 3 lines in length).
ngl bestie, "hints" is doing a lot of work in that sentence ๐Ÿ˜ญ don't be surprised when the formatter politely ignores you.

Here are some examples:

# perltidy -lp -vt=0 -vtc=0
%romanNumerals = (
                   one   => 'I',
                   two   => 'II',
                   three => 'III',
                   four  => 'IV',
);

# perltidy -lp -vt=1 -vtc=0
%romanNumerals = ( one   => 'I',
                   two   => 'II',
                   three => 'III',
                   four  => 'IV',
);

# perltidy -lp -vt=1 -vtc=1
%romanNumerals = ( one   => 'I',
                   two   => 'II',
                   three => 'III',
                   four  => 'IV', );

# perltidy -vtc=3
my_function(
    one   => 'I',
    two   => 'II',
    three => 'III',
    four  => 'IV', );

# perltidy -vtc=3
%romanNumerals = (
    one   => 'I',
    two   => 'II',
    three => 'III',
    four  => 'IV',
);

In the last example for -vtc=3, the opening paren is preceded by an equals so the closing paren is placed on a new line.

The difference between -vt=1 and -vt=2 is shown here:

# perltidy -lp -vt=1
$init->add(
            mysprintf( "(void)find_threadsv(%s);",
                       cstring( $threadsv_names[ $op->targ ] )
            )
);
# perltidy -lp -vt=2
$init->add( mysprintf( "(void)find_threadsv(%s);",
                       cstring( $threadsv_names[ $op->targ ] )
            )
);

โœจ With -vt=1, that line ending in add( does not smoosh together with the next line, because the next line isn't balanced. Honestly? kinda nice for readability. But bestie, if you wanna ignore that rule entirely, that's exactly what -vt=2 is for. ๐Ÿ’…

And if you want the tightest, least readable code in existence (iconic of you), use both "-vt=2" and "-vtc=2":

# perltidy -lp -vt=2 -vtc=2
$init->add( mysprintf( "(void)find_threadsv(%s);",
                       cstring( $threadsv_names[ $op->targ ] ) ) );

Notice how the code in all of these examples collapses vertically as -vt increases, but the indentation stays exactly the same. Why? Because perltidy implements the -vt parameter by first formatting as if -vt=0, and then just overwriting one output line on top of the next whenever it can, to hit the vertical tightness you asked for. The -lp (--line-up-parentheses) indentation style was literally designed to let this vertical collapse happen, which is why it's required for the -vt parameter. ๐Ÿซถ

The -vt=n and -vtc=n parameters apply to each type of container token. So if you want, you can apply vertical tightness controls independently to each of the closing container token types. ๐ŸŒธ

The parameters for controlling parens are -pvt=n or --paren-vertical-tightness=n, and -pvtc=n or --paren-vertical-tightness-closing=n.

Likewise, the parameters for square brackets are -sbvt=n or --square-bracket-vertical-tightness=n, and -sbvtc=n or --square-bracket-vertical-tightness-closing=n.

And finally, the parameters for controlling non-code block braces are -bvt=n or --brace-vertical-tightness=n, and -bvtc=n or --brace-vertical-tightness-closing=n.

Fun fact: -vt=n is actually just a shorthand for -pvt=n -bvt=n sbvt=n, and in the same way -vtc=n is shorthand for -pvtc=n -bvtc=n -sbvtc=n. ๐Ÿ’–

  • -bbvt=n or --block-brace-vertical-tightness=n โ€” the -bbvt=n flag is just like -vt=n but it applies to opening code block braces, slay.
-bbvt=0 break after opening block brace (default).
-bbvt=1 do not break unless this would produce more than one
        step in indentation in a line.
-bbvt=2 do not break after opening block brace.

Heads up bestie: you also have to use either -bl or -bli for this to actually work, because (same as the other vertical tightness controls) it's implemented by literally overwriting a line ending with an opening block brace with the line right after it. Like so:

# perltidy -bli -bbvt=0
if ( open( FILE, "< $File" ) )
  {
    while ( $File = <FILE> )
      {
        $In .= $File;
        $count++;
      }
    close(FILE);
  }

# perltidy -bli -bbvt=1
if ( open( FILE, "< $File" ) )
  { while ( $File = <FILE> )
      { $In .= $File;
        $count++;
      }
    close(FILE);
  }

By default this applies to blocks associated with the keywords if, elsif, else, unless, for, foreach, sub, while, until, and also with a preceding label. Wanna change that? Use the parameter -bbvtl=string, or --block-brace-vertical-tightness-list=string, where string is a space-separated list of block types. For the full deets on what values that string can take, go look at "Specifying Block Types". ๐ŸŒˆ

So for example, if we only want this style on if, elsif, and else blocks, we'd do perltidy -bli -bbvt=1 -bbvtl='if elsif else'. ๐ŸŽ€

There is no vertical tightness control for closing block braces. With one single exception, they get placed on separate lines. The exception? A cascade of closing block braces can be stacked on a single line. See --stack-closing-block-brace.

The -sot flag tells perltidy to "stack" opening tokens whenever it can, so you don't get sad little lines with one isolated opening token all alone. ๐Ÿ˜ญ

For example:

# default
$opt_c = Text::CSV_XS->new(
    {
        binary       => 1,
        sep_char     => $opt_c,
        always_quote => 1,
    }
);

# -sot
$opt_c = Text::CSV_XS->new( {
        binary       => 1,
        sep_char     => $opt_c,
        always_quote => 1,
    }
);

For detailed control over individual opening tokens, these controls are your besties:

-sop  or --stack-opening-paren
-sohb or --stack-opening-hash-brace
-sosb or --stack-opening-square-bracket
-sobb or --stack-opening-block-brace

The flag -sot is an abbreviation for -sop -sohb -sosb.

And the flag -sobb is an abbreviation for -bbvt=2 -bbvtl='*'. This will cause a cascade of opening block braces to appear on a single line โ€” although ngl that's a pretty uncommon occurrence except in test scripts. ๐Ÿ™ˆ


The -sct flag tells perltidy to "stack" closing tokens when possible, so you don't get lines with isolated closing tokens just vibing by themselves.

For example:

# default
$opt_c = Text::CSV_XS->new(
    {
        binary       => 1,
        sep_char     => $opt_c,
        always_quote => 1,
    }
);

# -sct
$opt_c = Text::CSV_XS->new(
    {
        binary       => 1,
        sep_char     => $opt_c,
        always_quote => 1,
    } );

The -sct flag is somewhat similar to the -vtc (--vertical-tightness-closing) flags, and in some cases it can give a similar result. The difference is that the -vtc flags try to avoid lines with leading opening tokens by "hiding" them at the end of a previous line, whereas the -sct flag just tries to reduce the number of lines with isolated closing tokens by stacking them โ€” it does not try to hide them. For example:

# -vtc=2
$opt_c = Text::CSV_XS->new(
    {
        binary       => 1,
        sep_char     => $opt_c,
        always_quote => 1, } );

For detailed control of the stacking of individual closing tokens, you've got:

-scp  or --stack-closing-paren
-schb or --stack-closing-hash-brace
-scsb or --stack-closing-square-bracket
-scbb or --stack-closing-block-brace

The flag -sct is an abbreviation for stacking the non-block closing tokens: -scp -schb -scsb.

Stacking of closing block braces, -scbb, causes a cascade of isolated closing block braces to be combined into a single line, like this:

# -scbb:
for $w1 (@w1) {
    for $w2 (@w2) {
        for $w3 (@w3) {
            for $w4 (@w4) {
                push( @lines, "$w1 $w2 $w3 $w4\n" );
            } } } }

And to make input even simpler for that case where both opening and closing non-block containers are stacked, the flag -sac or --stack-all-containers is an abbreviation for --stack-opening-tokens --stack-closing-tokens. ๐Ÿซถ

Ok so real talk: if both opening and closing tokens are gonna be stacked, the newer flag --weld-nested-containers may be preferable, because it insures that stacking is always done symmetrically. It also removes an extra level of unnecessary indentation within welded containers. It can do all that because it works on formatting globally rather than locally, the way --stack-opening-tokens and --stack-closing-tokens do. ๐Ÿ‘‘

๐Ÿฆ‹ Breaking Before or After Operators

Four command line parameters give you some control over whether a line break should come before or after specific token types. Two of them give detailed control:

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

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

Each of these parameters is followed by a quoted string, s, containing a list of token types (separated only by spaces). You should specify no more than one of each of these parameters, because repeating a command-line parameter always overwrites the previous one before perltidy ever even sees it. ๐Ÿ’€

By default, perltidy breaks after these token types:

% + - * / x != == >= <= =~ !~ < >  | &
= **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x=

And perltidy breaks before these token types by default:

. << >> -> && || //

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

-wba="."

Another example โ€” the following command would cause a break before the math operators +, -, /, and *:

-wbb="+ - / *"

These commands should work well for most of the token types that perltidy uses (use --dump-token-types for a list). Also try the -D flag on a short snippet of code and look at the .DEBUG file to see the tokenization. However, for a few token types there may be conflicts with hardwired logic, and that can cause unexpected results. One example is curly braces, which should be controlled with the parameter --opening-brace-on-new-line, which exists for exactly that purpose.

WARNING Be sure to put these tokens in quotes so your command shell doesn't misinterpret them. ๐Ÿ˜ญ

Two additional parameters are available which, though they provide no further capability, can simplify your input:

-baao or --break-after-all-operators,

-bbao or --break-before-all-operators.

The -baao sets the default to be to break after all of the following operators:

% + - * / x != == >= <= =~ !~ < > | &
= **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x=
. : ? && || and or err xor

and the -bbao flag sets the default to break before all of these operators. These can be used to define an initial break preference which you can then fine-tune with the --want-break-after and --want-break-before flags. For example, to break before all operators except an =, you could use "-bbao -wba='='" instead of listing every single perl operator except = on a -wbb flag. Genius, honestly. ๐Ÿ’…

  • -bal=n, --break-after-labels=n โ€” this flag controls whether or not a line break happens after a label. There are three possible values for n:
  • -bal=0 โ€” break if there is a break in the input [DEFAULT] ๐Ÿ’–
  • -bal=1 โ€” always break after a label, no cap
  • -bal=2 โ€” never break after a label, periodt

So like, for real for real, here's what that looks like in the wild:

# perltidy -bal=1
RETURN:
  return;

# perltidy -bal=2
RETURN: return;

Controlling List Formatting ๐ŸŽ€

okay bestie so perltidy tries to lay out lists of comma-separated values in these cute little tables that look good. And honestly? The default algorithms usually eat. But sometimes they just... don't. ๐Ÿ˜ญ And when they don't, you've got several methods in your toolbox to take back control.

The simplest hack ever: if you wanna stop perltidy from messing with your line breaks inside a comma-separated list, just drop a blank line, a comment, or a side-comment anywhere between the opening and closing parens (or braces or brackets). That's it. That makes perltidy skip right over its list formatting logic. (Why? Because any of those items puts a constraint on line breaks, and perltidy needs complete control over line breaks within a container to adjust a list layout โ€” and it's not about to fight you for it ๐Ÿ’…). For example, let's look at:

my @list = (1,
            1, 1,
            1, 2, 1,
            1, 3, 3, 1,
            1, 4, 6, 4, 1,);

The default formatting, which allows a maximum line length of 80, will flatten this down to one line:

# perltidy (default)
my @list = ( 1, 1, 1, 1, 2, 1, 1, 3, 3, 1, 1, 4, 6, 4, 1, );

Which is giving structural collapse. ๐Ÿ’€ This formatting loses the nice structure, ngl. But! The original line breaks can be retained by adding a comment or a blank line somewhere between the two parens. For example:

my @list = (
    1,    # a side comment forces the original breakpoints to be kept
    1, 1,
    1, 2, 1,
    1, 3, 3, 1,
    1, 4, 6, 4, 1,
);

We could achieve the same result with a blank line or full comment anywhere between the opening and closing parens. Vertical alignment of the list items will still occur if possible. The blank line method is shown here:

my @list = (

    1,
    1, 1,
    1, 2, 1,
    1, 3, 3, 1,
    1, 4, 6, 4, 1,
);

For another possibility see the -fs flag in "Skipping Selected Sections of Code". โœจ


  • -boc, --break-at-old-comma-breakpoints โ€” ngl this is another way to stop comma-separated lists from getting reformatted. Using -boc on the example above, plus additional flags to retain the original style, yields:
# perltidy -boc -lp -pt=2 -vt=1 -vtc=1
my @list = (1,
            1, 1,
            1, 2, 1,
            1, 3, 3, 1,
            1, 4, 6, 4, 1,);

Downside compared to the methods we just talked about? Literally every single table in the file has to already be nicely formatted. No pressure or anything. ๐Ÿ™ˆ

  • -btct=s, --break-at-trailing-comma-types=s โ€” a trailing comma is an optional comma following the last item of a list (iykyk). -btct=s tells perltidy to end a line at selected trailing commas. The string s selects which trailing commas, like so:
s=1 or '*' : every trailing comma
s=m a trailing comma in a multiline list
s=b a bare trailing comma
s=0 none

For example, given the following input

$w->bind(
    '<Page_Down>' => xx,
);

The default formatting would flatten this into a single line. But the container can be kept open with

# perltidy -btct='b'
$w->bind(
    '<Page_Down>' => xx,
);

This can be particularly useful for short function calls like this, where the default perltidy formatting does not keep the container open. ๐Ÿซถ

The options s=m and s=1 can be used to open up containers with non-bare trailing commas. For example, given this input

$w->bind( '<Page_Down>' => xx, );

we can break it open with

# perltidy -btct=1
$w->bind(
    '<Page_Down>' => xx,
);

Afterwards, we could switch to -btct='b' since the trailing comma is now bare. But the -btct parameter must be retained in this case because otherwise this small list will be flattened the next time it is formatted. ๐Ÿ˜ค

This logic can be restricted to specific container types by including an opening token ahead of the letter in the above table. For example

-btct='(b'

means that this operation should only apply to bare trailing commas within parentheses.

For parentheses, an additional item of information which can be given is an alphanumeric letter which is used to limit the selection further depending on the type of token immediately before the opening paren. The possible letters are currently 'k', 'K', 'f', 'F', 'w', and 'W', with these meanings for matching whatever precedes an opening paren:

'k' matches if the previous nonblank token is a perl keyword
    (such as 'if', 'while'),
'K' matches if 'k' does not: previous token is not a keyword
'f' matches if previous token is a function (not a keyword)
'F' matches if 'f' does not.
'w' matches if either 'k' or 'f' match.
'W' matches if 'w' does not.

These are the same codes used for --line-up-parentheses-inclusion-list. For example,

-btct='f(b'

means that bare trailing commas in function call lists in the input stream should be followed by line breaks in the formatted output stream.

The section "Adding and Deleting Commas" describes additional controls for working with trailing commas. These can be combined with the -break-trailing-comma-types parameter for additional control of list formatting. ๐ŸŒธ

  • -mft=n, --maximum-fields-per-table=n โ€” if n is a positive number, and the computed number of fields for any table exceeds n, then it will be reduced to n. This parameter might be used on a small section of code to force a list to have a particular number of fields per line, and then either the -boc flag could be used to retain this formatting, or a blank line or comment could be introduced somewhere to freeze the formatting in future applications of perltidy. For example
# perltidy -mft=2
@month_of_year = (
    'Jan', 'Feb',
    'Mar', 'Apr',
    'May', 'Jun',
    'Jul', 'Aug',
    'Sep', 'Oct',
    'Nov', 'Dec'
);

The default value is n=0, which does not place a limit on the number of fields in a table. Very much a "no thoughts, head empty, no limits" situation ๐Ÿ’œ

  • -cab=n, --comma-arrow-breakpoints=n โ€” a comma which follows a comma arrow, '=>', is given special consideration. In a long list, it is common to break at all such commas. This parameter can be used to control how perltidy breaks at these commas. (However, it will have no effect if old comma breaks are being forced because -boc is used). The possible values of n are:
n=0 break at all commas after =>
n=1 stable: break at all commas after => if container is open,
    EXCEPT FOR one-line containers
n=2 break at all commas after =>, BUT try to form the maximum
    one-line container lengths
n=3 do not treat commas after => specially at all
n=4 break everything: like n=0 but ALSO break a short container with
    a => not followed by a comma when -vt=0 is used
n=5 stable: like n=1 but ALSO break at open one-line containers when
    -vt=0 is used (default)

For example, given the following single line, perltidy by default will not add any line breaks because it would break the existing one-line container:

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

Using -cab=0 will force a break after each comma-arrow item:

# perltidy -cab=0:
bless {
    B    => $B,
    Root => $Root
} => $package;

If perltidy is subsequently run with this container broken, then by default it will break after each '=>' because the container is now broken. To reform a one-line container, the parameter -cab=2 could be used.

The flag -cab=3 can be used to prevent these commas from being treated specially. In this case, an item such as "01" => 31 is treated as a single item in a table. The number of fields in this table will be determined by the same rules that are used for any other table. Here is an example.

# perltidy -cab=3
my %last_day = (
    "01" => 31, "02" => 29, "03" => 31, "04" => 30,
    "05" => 31, "06" => 30, "07" => 31, "08" => 31,
    "09" => 30, "10" => 31, "11" => 30, "12" => 31
);
  • -qwaf, --qw-as-function โ€” this option tells perltidy to format a qw list which is delimited with parentheses as if it were a function call whose call args are a list of quoted items. Normally, a qw list is output verbatim except for an adjustment of leading whitespace to indicate the indentation level. For example, here is an example of the default formatting of a poorly formatted qw list:
# perltidy
@fields = qw( $st_dev     $st_ino    $st_mode $st_nlink   $st_uid
  $st_gid $st_rdev    $st_size $st_atime   $st_mtime  $st_ctime
  $st_blksize $st_blocks);

If we format with -qwaf then the result will be:

# perltidy -qwaf
@fields = qw(
    $st_dev   $st_ino   $st_mode  $st_nlink
    $st_uid   $st_gid   $st_rdev  $st_size
    $st_atime $st_mtime $st_ctime $st_blksize
    $st_blocks
);

GLOW UP. ๐Ÿ˜ญโœจ

The way this works is that just before formatting begins, the tokens of the qw text are replaced with the tokens of an equivalent function call with a comma-separated list of quoted items as call args. Then it is formatted like any other list. Special comma tokens are employed which have no display text, so when the code is eventually displayed it remains a valid qw quote. Sneaky but iconic, honestly. ๐Ÿ‘‘

Some things to note are:

  • This only works for qw quotes which begin with qw(, with no space before the paren.
  • If the option --space-function-paren is employed, it is ignored for these special function calls because it would deactivate them.
  • Otherwise the various formatting control flags operate on these lists the same as for other comma-separated lists. In particular, note that if --break-at-old-comma-breakpoints, or -boc, is set, then the old line break locations will be retained. And old line breaks will be retained if there are any blank lines between the opening and closing parens. ๐Ÿ’…
  • Before using this option for the first time, it is a good idea to scan the code and decide if any lists have a special order which should be retained. This can be accomplished for example by changing the quote delimiters to something other than parens, or by inserting a blank line as discussed at the start of this section. ๐Ÿ‘‘

Adding and Deleting Commas ๐ŸŽ€

  • -drc, --delete-repeated-commas โ€” okay so this one yeets the repeated commas. Like, given this lil list with a repeated comma in it
      ignoreSpec( $file, "file",, \%spec, \%Rspec );

we can remove it with -drc

      # perltidy -drc:
      ignoreSpec( $file, "file", \%spec, \%Rspec );

This parameter also deletes repeated fat commas, '=>'. The complete list of actions taken when this flag is set are as follows:

  • Repeated commas like ',,' are removed with a warning. ๐Ÿ˜ญ
  • Repeated fat commas like '=> =>' are removed with a warning.
  • The combination '=>,' produces a warning but is not changed (it is likely an error but only its author would know how to fix it). ๐Ÿ’€
  • The remaining combination ',=>' (sometimes called a 'winking fat comma') is ignored by this parameter.
  • These warnings are only output if the --warning-output, or -w, flag is set.

This option is on by default. Use -ndrc to turn it off.

Adding and Deleting Trailing Commas ๐Ÿฆ‹

A trailing comma is a comma following the last item of a list. Perl allows trailing commas but they are not required. Including them can sometimes simplify the maintenance of large or complex lists, and help display structure. But they may not be appropriate in all lists, for example in a list which always has just one term. By default, perltidy does not add or delete trailing commas, but it is possible to manipulate them with the following set of related parameters:

  • --want-trailing-commas=s, -wtc=s - defines where trailing commas are wanted (the style) โœจ
  • --add-trailing-commas, -atc - gives permission to add trailing commas to match the style wanted
  • --delete-trailing-commas, -dtc - gives permission to delete trailing commas which do not match the style wanted

The parameter --want-trailing-commas=s, or -wtc=s, defines a preferred style. The string s indicates which lists should get trailing commas, as follows:

 s=1 or '*' : every list
 s=m a multiline list
 s=b a multiline list, bare trailing comma
 s=i a multiline list, bare trailing comma, about one comma per line
 s=h a multiline list, bare trailing comma, about one key=>value
       pair per line
 s=0 : no list

 s=' ' or not defined : leave trailing commas unchanged [DEFAULT]

where:

  • A list here is basically taken to be a container of items (parens, square brackets, or braces), which is not a code block, which contains one or more commas or fat commas. These parameters only apply to something that fits this definition of a list.

A paren-less list of parameters is not a list by this definition, so these parameters do not apply to a paren-less list. ๐Ÿ™ˆ

  • A multiline list is a list for which the opening and closing brackets on different lines.
  • A bare trailing comma is a comma which is at the end of a line. That is, the closing container token follows on a different line. So a list with a bare trailing comma is a special case of a multiline list.
  • In fact the above options for trailing commas can be seen as a hierarchy of nesting sets which can be expressed as
    1 > m > b > i > h > 0

This indicates that multiline trailing commas m are a subset of all trailing commas, and bare trailing commas b are a subset of all multiline trailing commas, and so on. ๐ŸŒธ

This parameter by itself only indicates where trailing commas are wanted. Perltidy only adds these trailing commas if permission is granted by setting the flag --add-trailing-commas, or -atc. And perltidy only removes unwanted trailing commas if the flag --delete-trailing-commas, or -dtc is set.

Here are some example parameter combinations and their meanings

 -wtc=0 -dtc   : delete all trailing commas
 -wtc=1 -atc   : add trailing commas to all lists
 -wtc=m -atc   : add trailing commas to all multiline lists
                 (single line lists remain unchanged)
 -wtc=b -atc   : add commas so that all lists whose closing
                 bracket starts a new line have trailing commas
 -wtc=b -dtc   : all trailing commas which are not bare
                 (not followed by a newline) get deleted.
 -wtc=b -atc -dtc  : do both of the above operations so that
                     all trailing commas are bare

For example, given the following input

    $wine_list = $top->Box(
        "-length" => 5,
        "-width"  => 3
    )->select( "red", "white", "gold", );

we have

    # perltidy -wtc=b -atc -dtc
    $wine_list = $top->Box(
        "-length" => 5,
        "-width"  => 3,
    )->select( "red", "white", "gold" );

A comma was added after the 3, since it is bare, and a comma was removed after "gold", since it not bare. ๐Ÿ’…

It is possible to apply a different style to each type of container token by including an opening token ahead of the style character in the above table. For example

    -wtc='(m [b'

means that lists within parens should have multiline trailing commas, and that lists within square brackets have bare trailing commas. Since there is no specification for curly braces in this example, their trailing commas would remain unchanged.

For parentheses, an additional item of information which can be given is an alphanumeric letter which is used to limit the selection further depending on the type of token immediately before the opening paren. The possible letters are currently 'k', 'K', 'f', 'F', 'w', and 'W', with these meanings for matching whatever precedes an opening paren:

 'k' matches if the previous nonblank token is a perl keyword
     (such as 'if', 'while'),
 'K' matches if 'k' does not: previous token is not a keyword
 'f' matches if previous token is a function (not a keyword)
 'F' matches if 'f' does not.
 'w' matches if either 'k' or 'f' match.
 'W' matches if 'w' does not.

These are the same codes used for --line-up-parentheses-inclusion-list. For example,

  -wtc='w(m'

means that trailing commas are wanted for multiline parenthesized lists following a function call or keyword.

Finally, a leading + can be placed on any term to indicate that it only applies when adding commas. A leading - indicates that it only applies when deleting commas. For example,

  -wtc='+h -b' -atc -dtc

means that missing trailing commas should be added to lists of key => value pairs, and trailing commas which are not bare should be removed. No other changes are made. When both plus and minus terms are used like this, they must not be in conflict. There is no conflict in this example because the trailing comma locations of the key=>value pairs selected by the +h term are a subset of all bare trailing commas, and thus will not be deleted by the -b term. The general rule is that the letter of the plus term should occur after the letter of the minus term in the hierarchical nesting order, 1 > m > b > i > h > 0. ๐Ÿ‘‘

Some points to note regarding adding and deleting trailing commas:

  • It is recommended to also use the --converge parameter when adding and/or deleting trailing commas, especially if the formatter may be making other line break changes at the same time. The reason is that the decision regarding whether or not a list is multiline or bare is made based on the input stream if only one iteration is made, which is the default.

When iterations are requested with the --converge parameter, any comma deletion operations are postponed until the start of the second iteration, after most changes in line breaks have been made.

To illustrate, if we start with

          f(
              a => 1,
              b => 2, );

and attempt to delete non-bare commas,

          # perltidy -wtc=b -dtc
          f(
              a => 1,
              b => 2
          );

we delete a comma which has become bare, which is not what is wanted. This happened because the change was based on the starting rather than the final line breaks. Running with --converge gives the desired result:

          # perltidy -wtc=b -dtc --converge
          f(
              a => 1,
              b => 2,
          );

because comma changes are based on the line breaks after the first iteration.

A parameter --delay-trailing-comma-operations, or -dtco, is available to control this behavior if desired. Negating this parameter, with -ndtco, tells perltidy to always use the starting state to make decisions regarding comma addition and deletion, even when iterations are requested. This should not normally be necessary. ๐Ÿ˜ญ

  • Perltidy does not add a trailing comma in some edge cases which appear to be near a stability limit. So if a comma is unexpectedly not added, this is probably the reason. ๐Ÿ’€
  • If the parameter --break-at-trailing-comma-types, or -btct. is also employed, it operates on the state after any adding or deleting of commas. And it will allow trailing commas to be added in most edge cases. For example, given the following input text
  plot(
      'g', Canvas => $overview_canvas
  );

so like, formatting with -wtc=f(b) -atc will not add a trailing comma, because the list gets flattened and the comma wouldn't stay bare. but bestie, we can add a trailing comma and keep the container open, like this:

# perltidy -wtc='f(b' -atc -btct='f(b'
plot(
    'g', Canvas => $overview_canvas,
);

ok another example โ€” same text on a single line, no trailing comma:

plot( 'g', Canvas => $overview_canvas );

we can add a trailing comma and break the container open with this:

# perltidy -wtc=1 -atc -btct=1
plot(
    'g', Canvas => $overview_canvas,
);

and then after that, we could use -btct='f(b' to keep the container open. iconic.

  • when you're using these parameters for the first time, please do yourself a favor and practice on some test scripts, then verify the results are actually what you expected. slay responsibly ๐Ÿ’…

Special Considerations for Lone Trailing Commas ๐ŸŽ€

adding or deleting the only comma in a list can have some implications, so let's unpack them (and possibly control them). two extra controls exist just for these lone commas:

  • --add-lone-trailing-commas, -altc โ€” gives permission to add a comma if it will be the only comma. this is on by default and explained below.
  • --delete-lone-trailing-commas, -dltc โ€” gives permission to delete the only comma in a list. this is on by default and explained below.

ok so one issue with deleting a lone comma: if it gets deleted, it might not be possible to add it back automatically, because perltidy uses the existence of commas to help locate containers where commas are appropriate. like, given:

my ( $self, ) = @_;

and if we remove the comma with:

# perltidy -wtc=m -dtc
my ( $self ) = @_;

then we cannot use the trailing comma controls to add that comma back. the parameter --delete-lone-trailing-commas allows such a comma to be deleted, and it's on by default, but you can turn it off to prevent this. this might be useful if you're experimenting with formatting options and want to restrict testing to operations which are reversible. note that this parameter is a fine-tuning control for --delete-trailing-commas, which must also be set for it to have any effect. iykyk.

however!! if a single item in a list is itself a list with multiple lines, like the item in braces here:

$self->make_grammar(
    {
        iterator => $self->_iterator,
        parser   => $self,
    }
);

then perltidy can add and/or delete a lone comma:

# perltidy -atc -wtc=b
$self->make_grammar(
    {
        iterator => $self->_iterator,
        parser   => $self,
    },
);

but it turns out these cases usually coincide with situations where the --weld-nested-containers, or -wn, parameter would apply, and adding such commas can block welding. for example, the -wn parameter would succeed on the first of the above snippets, but it would fail on the second because of the added trailing comma. ๐Ÿ˜ญ

the parameter --add-lone-trailing-commas, or -altc, allows these commas to be added, provided that --add-trailing-commas is also set. it's on by default. users of -wn may want to turn it off with --noadd-lone-trailing-commas, -naltc to prevent such commas from being added.

if such commas do get added, then they can be removed to allow welding with the control described in the next section. ๐Ÿซถ

-dwic, --delete-weld-interfering-commas

if the closing tokens of two nested containers are separated by a comma, then welding requested with --weld-nested-containers cannot occur. any commas in this situation are optional trailing commas and can be removed with -dwic. for example, a comma in this script prevents welding:

# perltidy -wn
$self->make_grammar(
    {
        iterator => $self->_iterator,
        parser   => $self,
    },
);

adding -dwic removes the comma and allows welding:

# perltidy -wn -dwic
$self->make_grammar( {
    iterator => $self->_iterator,
    parser   => $self,
} );

this feature is off by default. here are some points to note about the -dwic parameter:

  • this operation is not always reversible, so please check results of using this parameter carefully. ๐Ÿ‘€
  • removing this type of isolated trailing comma is necessary for welding to be possible, but not sufficient. so welding will not always occur where these commas are removed.
  • this operation is independent of --add-trailing-commas and --delete-trailing-commas. if it conflicts with any of those settings, it has priority.

Adding and Deleting Interbracket Arrows ๐Ÿน

in the following expression, the arrow operator -> between the closing and opening brackets of hash keys and array indexes are optional:

return $self->{'commandline'}->{'args'}->[0]->[0]->{'hgroups'};

these will be called interbracket arrows here, for lack of a better term. perltidy will not change them by default, but they can be added or removed with the following parameters.

-dia, --delete-interbracket-arrows

this parameter deletes interbracket arrows. applied to the above example we have:

# perltidy -dia
return $self->{'commandline'}{'args'}[0][0]{'hgroups'};

by default this applies to all interbracket arrows, but selective deletion is possible with controls described below.

-aia, --add-interbracket-arrows

this parameter adds interbracket arrows. applied to the line of code above, we get back the original line:

# perltidy -aia
return $self->{'commandline'}->{'args'}->[0]->[0]->{'hgroups'};

selective changes can be made with controls described below.

-ias=s, --interbracket-arrow-style=s

by default the -add- and -delete- parameters apply to all interbracket arrows.

an optional style can be specified with this parameter string s. in that case the parameters --add-interbracket-arrows and --delete-interbracket-arrows only apply where they would bring the formatting into agreement with the specified style. they may both be used in a single run if a mixed style is specified, since there is no conflict.

the style string s gives a graphical description of the desired style. it lists up to four possible pairs of bracket types with an optional arrow between them. for example:

-ias='][   }->{'

this means no arrows are wanted between '][ but arrows should be between '}{'. and it means that the unlisted pairs ']{' and '}[ should remain unchanged, either with or without arrows.

in this particular example, if the parameter --delete-interbracket-arrows is used, then only arrows like ']->[' will be deleted, since they are the only ones which disagree with the style.

and likewise, if --add-interbracket-arrows is used, then arrows will only be inserted between brackets like '}{' to bring the formatting into conformity with the style in this example.

spaces in the string s are optional. they are ignored when the expression is parsed.

the style corresponding to all possible arrows is:

-ias=']->[ ]->{ }->[ }->{'

for convenience, this may also be requested with -ias=1 or -ias='*'.

the style corresponding to no interbracket arrows is:

-ias=']  [ ]  { }  [ }  {'

which may also be requested with -ias=0.

-wia, --warn-interbracket-arrows

if this parameter is set, then a message is written to the error file in the following cases:

  • if an arrow is added or deleted by an add or delete command.
  • if a style is defined and an arrow would have been added or deleted if requested. so for example, the command
perltidy -wia -ias=']['

will show where a file has arrows like ]->[ since they do not match the style, but no changes will be made because the delete command -dia has not been given. and

perltidy -wia -ias=0

will warn if any arrows exist, since the flag -ias=0 means that no arrows are wanted.

-iac=n, --interbracket-arrow-complexity=n

this parameter makes it possible to skip adding or deleting arrows following a container which is complex in some sense. three levels of complexity can be specified with the integer n, as follows:

n=0  the left container must contain be a single thing (token)
n=1  the left container must not contain other containers [DEFAULT]
n=2  the left container may contain anything

some examples:

# Container               complexity
{'commandline'}           0 single token         OK by default
{ $type . $name }         1 multiple tokens      OK by default
[ $plot{'x-axis'} - 1 ]   2 contains a container SKIPPED by default

so, with the default complexity level of 1, an arrow could be added or deleted following the first two of these containers but not the third.

some points to consider when working with these parameters are:

  • there are no known bugs, but this is a relatively new feature. so please carefully check file differences and run tests when interbracket arrows are added or removed. ๐Ÿ™ˆ
  • for some unusual spacing parameters, it could take an extra iteration for the spaces between brackets to reach their final state after arrows are added or deleted.
  • any comments between brackets will prevent the adding and deleting of arrows.

Missing Else Blocks ๐Ÿ’€

a defensive programming technique is to require that every if-elsif-chain be terminated with an else block, even though it is not strictly required. this helps insure that there are no holes in the logic.

for example, consider the following snippet:

my $type = get_cards();
if    ( $type = 1 ) { action("hold 'em") }
elsif ( $type = 2 ) { action("fold 'em") }
elsif ( $type = 3 ) { action("walk away") }

Okay so like... what if $type is some other value?? ๐Ÿ™ˆ When the code was brand-new it probably seemed super obvious that this was fine, but bestie, flash forward a few years and someone's reviewing this at 2am and it is not giving clarity. A terminal else block with a comment in it? That would lowkey save them. ๐Ÿ‘‘

Good news: the parameters in this section can help by either throwing a warning when an else is missing, or straight up inserting an empty else block where one's missing, or both. Choose your fighter. ๐Ÿ’…

  • -wme, --warn-missing-else โ€” tells perltidy to issue a warning if a program is missing a terminal else block. The default is not to issue such a warning.
  • -ame, --add-missing-else โ€” tells perltidy to output an empty else block wherever a program is missing a terminal else block. Wanna get a warning while it does that? You should also set -wme. The default is not to add missing else blocks.
  • -amec=s, --add-missing-else-comment=s โ€” this string is a side comment which will be written to highlight a brand new empty else block. The default is:
-amec='##FIXME - added with perltidy -ame'

For example, on the above example we can add a missing else and also get a warning notice with:

# perltidy -ame -wme
my $type = get_cards();
if    ( $type == 1 ) { action("hold 'em") }
elsif ( $type == 2 ) { action("fold 'em") }
elsif ( $type == 3 ) { action("walk away") }
else {
    ##FIXME - added with perltidy -ame
}
Any ##FIXME comments created in this way should be reviewed and changed appropriately. Like, perltidy is not your therapist, it just flags the vibe. ๐Ÿšฉ

For example, one might decide that the code is fine as is, and just change the comment to indicate that nothing has been overlooked:

my $type = get_cards();
if    ( $type == 1 ) { action("hold 'em") }
elsif ( $type == 2 ) { action("fold 'em") }
elsif ( $type == 3 ) { action("walk away") }
else {
    # ok - no worries
}

Or maybe a deeper analysis reveals that something was missed:

my $type = get_cards();
if    ( $type == 1 ) { action("hold 'em") }
elsif ( $type == 2 ) { action("fold 'em") }
elsif ( $type == 3 ) { action("walk away") }
else                 { action("run") }

Sometimes it turns out that the else block should not be reachable, in which case an error exit might be appropriate. In any case, having the else block can improve code maintainability. ๐Ÿซถ


๐ŸŒˆ Retaining or Ignoring Existing Line Breaks ๐ŸŒˆ

Several additional parameters are available for controlling the extent to which line breaks in the input script influence the output script. In most cases, the default parameter values are set so that, if a choice is possible, the output style follows the input style. For example, if a short logical container is broken in the input script, then the default behavior is for it to remain broken in the output script. Respect for the original, we love to see it. โœจ

Most of the parameters in this section would only be required for a one-time conversion of a script from short container lengths to longer container lengths. The opposite effect โ€” converting long container lengths to shorter lengths โ€” can be obtained by temporarily using a short maximum line length. Cute trick, no cap. ๐Ÿ’…

  • -bol, --break-at-old-logical-breakpoints โ€” by default, if a logical expression is broken at a "&&", "||", "and", or "or", then the container will remain broken. Also, breaks at internal keywords "if" and "unless" will normally be retained. To prevent this, and thus form longer lines, use -nbol.

Please note that this flag does not duplicate old logical breakpoints. They are merely used as a hint with this flag that a statement should remain broken. Without this flag, perltidy will normally try to combine relatively short expressions into a single line.

For example, given this snippet:

return unless $cmd = $cmd || ($dot
    && $Last) || &prompt('|');

# perltidy -bol [default]
return
  unless $cmd = $cmd
  || ( $dot
    && $Last )
  || &prompt('|');

# perltidy -nbol
return unless $cmd = $cmd || ( $dot && $Last ) || &prompt('|');
  • -bom, --break-at-old-method-breakpoints โ€” by default, a method call arrow "->" is considered a candidate for a breakpoint, but method chains will fill to the line width before a break is considered. With -bom, breaks before the arrow are preserved, so if you have pre-formatted a method chain:
# perltidy -bom
$Document
  ->schild(0)
  ->schildren();

the flag -bom will keep these line breaks, rather than become this:

# perltidy [DEFAULT]
$Document->schild(0)->schildren();

This flag will also look for and keep a 'cuddled' style of calls, in which lines begin with a closing paren followed by a call arrow, as in this example:

# perltidy -bom
my $q = $rs->related_resultset(
    'CDs'
)->related_resultset(
    'Tracks'
)->search(
    {
        'track.id' => { -ident => 'none_search.id' },
    }
)->as_query;
  • -bos, --break-at-old-semicolon-breakpoints โ€” semicolons are normally placed at the end of a statement. This means that formatted lines do not normally begin with semicolons. If the input stream has some lines which begin with semicolons, these can be retained by setting this flag. For example, consider the following two-line input snippet:
$z = sqrt($x**2 + $y**2)
;

The default formatting will be:

$z = sqrt( $x**2 + $y**2 );

Using the -bos flag keeps the isolated semicolon:

# perltidy -bos
$z = sqrt( $x**2 + $y**2 )
  ;

The extra continuation indentation spaces on the semicolon can be removed by also setting --noindent-leading-semicolon.

# perltidy -bos -nils
$z = sqrt( $x**2 + $y**2 )
;

The default is not to do this, -nbos.

  • -bok, --break-at-old-keyword-breakpoints โ€” by default, perltidy will retain a breakpoint before keywords which may return lists, such as "sort" and "map". This allows chains of these operators to be displayed one per line. Use -nbok to prevent retaining these breakpoints.
  • -bot, --break-at-old-ternary-breakpoints โ€” by default, if a conditional (ternary) operator is broken at a ":", then it will remain broken. To prevent this, and thereby form longer lines, use -nbot.
  • -boa, --break-at-old-attribute-breakpoints โ€” by default, if an attribute list is broken at a ":" in the source file, then it will remain broken. For example, given the following code, the line breaks at the ':'s will be retained:
my @field
  : field
  : Default(1)
  : Get('Name' => 'foo') : Set('Name');

If the attributes are on a single line in the source code then they will remain on a single line if possible.

To prevent this, and thereby always form longer lines, use -nboa.

โœจ Keeping old breakpoints at specific token types โœจ

It is possible to override the choice of line breaks made by perltidy, and force it to follow certain line breaks in the input stream, with these two parameters:

-kbb=s or --keep-old-breakpoints-before=s, and

-kba=s or --keep-old-breakpoints-after=s

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

For example, -kbb='=>' means that if an input line begins with a '=>' then the output script should also have a line break before that token.

For example, given the script:

method 'foo'
  => [ Int, Int ]
  => sub {
    my ( $self, $x, $y ) = ( shift, @_ );
    ...;
  };

# perltidy [default]
method 'foo' => [ Int, Int ] => sub {
    my ( $self, $x, $y ) = ( shift, @_ );
    ...;
};

# perltidy -kbb='=>'
method 'foo'
  => [ Int, Int ]
  => sub {
    my ( $self, $x, $y ) = ( shift, @_ );
    ...;
  };

For the container tokens '{', '[' and '(' and their closing counterparts, use the token symbol. Thus, the command to keep a break after all opening parens is:

perltidy -kba='('

It is possible to be more specific in matching parentheses by preceding them with a letter. The possible letters are 'k', 'K', 'f', 'F', 'w', and 'W', with these meanings (these are the same as used in the --weld-nested-exclusion-list and --line-up-parentheses-exclusion-list parameters):

  • 'k' matches if the previous nonblank token is a perl keyword (such as 'if', 'while'),
  • 'K' matches if 'k' does not: previous token is not a keyword
  • 'f' matches if previous token is a function (not a keyword)
  • 'F' matches if 'f' does not.
  • 'w' matches if either 'k' or 'f' match.
  • 'W' matches if 'w' does not.

So for example the following parameter will keep breaks after opening function call parens:

perltidy -kba='f('
NOTE: a request to break before an opening container, such as -kbb='(', will be silently ignored because it can lead to formatting instability. Likewise, a request to break after a closing container, such as -kba=')', will also be silently ignored. Bestie, it's not a bug, it's a boundary. ๐Ÿšซ
  • -iob, --ignore-old-breakpoints โ€” use this flag to tell perltidy to ignore existing line breaks to the maximum extent possible. This will tend to produce the longest possible containers, regardless of type, which do not exceed the line length limit. But please note that this parameter has priority over all other parameters requesting that certain old breakpoints be kept. ๐Ÿ‘‘

To illustrate, consider the following input text:

has subcmds => (
    is => 'ro',
    default => sub { [] },
);

The default formatting will keep the container broken, giving

# perltidy [default]
has subcmds => (
    is      => 'ro',
    default => sub { [] },
);

If old breakpoints are ignored, the list will be flattened:

# perltidy -iob
has subcmds => ( is => 'ro', default => sub { [] }, );

And bestie, it's not just lists!! โœจ Besides flattening lists, this parameter also applies to lines that got broken at certain logical breakpoints, like around if and or. And here's the cute part: even if you're not using this thing globally, it's a genuinely convenient way to flatten selected lists from inside your editor. Chef's kiss. ๐Ÿซถ

  • -kis, --keep-interior-semicolons โ€” use this flag to stop perltidy from breaking at a semicolon if there was no break there in the input file. Normally perltidy drops a newline after every semicolon that terminates a statement โ€” unless several statements are hanging out inside a one-line brace block. Okay so picture these input lines:
dbmclose(%verb_delim); undef %verb_delim;
dbmclose(%expanded); undef %expanded;

The default behaviour is to break after each statement, which gives you:

dbmclose(%verb_delim);
undef %verb_delim;
dbmclose(%expanded);
undef %expanded;

But with perltidy -kis the multiple statements are retained:

dbmclose(%verb_delim); undef %verb_delim;
dbmclose(%expanded);   undef %expanded;

Those statements are still subject to the specified value of maximum-line-length though โ€” if this maximum gets exceeded, they're getting broken. No exceptions, no cap. ๐Ÿ’€


๐Ÿ› Blank Line Control ๐Ÿ›

Blank lines can genuinely level up a script's readability if they're placed with intention. Carelessly sprinkled blanks? It's giving chaos. Perltidy has a whole lil toolkit for controlling the insertion, retention, and removal of blank lines. ๐Ÿ’–

  • -fbl, --freeze-blank-lines โ€” set -fbl when you want the blank lines in your script to stay exactly as they are. Once you do that, the rest of the parameters in this section can just be ignored. (Note: setting the -fbl flag is equivalent to setting -mbl=0 and -kbl=2.) ๐ŸงŠ
  • -bbc, --blanks-before-comments โ€” a blank line gets introduced before a full-line comment. This is the default. Use -nbbc or --noblanks-before-comments to stop those blank lines from being introduced.
  • -blbs=n, --blank-lines-before-subs=n โ€” -blbs=n requests that at least n blank lines precede a sub definition that does not follow a comment and that is more than one line long. Default is -blbs=1. BEGIN and END blocks count too, bestie.

The requested number of blanks will be inserted regardless of the value of --maximum-consecutive-blank-lines=n (-mbl=n) โ€” with the exception that if -mbl=0, then no blanks will be output at all.

This parameter interacts with the value k of the parameter --maximum-consecutive-blank-lines=k (-mbl=k) like so:

  1. If -mbl=0 then no blanks will be output. This lets you suppress all blanks with a single parameter. Otherwise,
  2. If the number of old blank lines in the script is less than n then additional blanks will be inserted to make the total n, regardless of the value of -mbl=k.
  3. If the number of old blank lines in the script equals or exceeds n then this parameter has no effect โ€” however the total will not exceed the value specified on the -mbl=k flag.
  • -blbp=n, --blank-lines-before-packages=n โ€” -blbp=n requests that at least n blank lines precede a package which does not follow a comment. The default is -blbp=1.

This parameter interacts with the value k of the parameter --maximum-consecutive-blank-lines=k (-mbl=k) in exactly the same way as described for the previous item, -blbs=n. ๐Ÿ‘ฏ

  • -bbs, --blanks-before-subs โ€” for compatibility with previous versions, -bbs or --blanks-before-subs is equivalent to -blbp=1 and -blbs=1.

Likewise, -nbbs or --noblanks-before-subs is equivalent to -blbp=0 and -blbs=0.

  • -bbb, --blanks-before-blocks โ€” a blank line will be introduced before blocks of coding delimited by for, foreach, while, until, and if, unless, in the following circumstances:
    • The block is not preceded by a comment.
    • The block is not a one-line block.
    • The number of consecutive non-blank lines at the current indentation depth is at least -lbl (see next section).

This is the default. The intention of this option is to introduce some space within dense coding. It's negated with -nbbb or --noblanks-before-blocks. ๐Ÿงฑ

  • -lbl=n, --long-block-line-count=n โ€” this controls how often perltidy is allowed to add blank lines before certain block types (see the previous section). The default is 8. And listen: entering a value of 0 is equivalent to entering a very large number. Yes, seriously. ๐Ÿ˜ญ
  • -blao=i or --blank-lines-after-opening-block=i โ€” this control places a minimum of i blank lines after a line which ends with an opening block brace of a specified type. By default this only applies to the block of a named sub, but that can be changed (see -blaol below). The default is not to do this (i=0).

Please see the note below on using the -blao and -blbc options. ๐Ÿ™

  • -blbc=i or --blank-lines-before-closing-block=i โ€” this control places a minimum of i blank lines before a line which begins with a closing block brace of a specified type. By default this only applies to the block of a named sub, but that can be changed (see -blbcl below). The default is not to do this (i=0).
  • -blaol=s or --blank-lines-after-opening-block-list=s โ€” the parameter s is a list of block type keywords to which the flag -blao should apply. The section "Specifying Block Types" explains how to list block types.
  • -blbcl=s or --blank-lines-before-closing-block-list=s โ€” this parameter is a list of block type keywords to which the flag -blbc should apply. The section "Specifying Block Types" explains how to list block types.

๐Ÿ“Œ Note on using the -blao and -blbc options ๐Ÿ“Œ

These blank line controls introduce a certain minimum number of blank lines into the text โ€” but the final number of blank lines may be greater, depending on the values of the other blank line controls and the number of old blank lines. The consequence, and I need you to hear me on this one: introducing blank lines with these and other controls cannot be exactly undone. So please, some experimentation with these controls is recommended before you actually use them. ๐Ÿงช

For example, suppose that for some reason we decide to introduce one blank space at the beginning and ending of all blocks. We could do this using

perltidy -blao=2 -blbc=2 -blaol='*' -blbcl='*' filename

Now suppose the script continues to be developed, but at some later date we decide we don't want these spaces after all. We might expect that running with the flags -blao=0 and -blbc=0 will undo them. However, by default perltidy retains single blank lines, so the blank lines remain. ๐Ÿ˜ญ

We can easily fix this by telling perltidy to ignore old blank lines, by including the added parameter --keep-old-blank-lines=0 and rerunning. Then the unwanted blank lines will be gone. However โ€” this will cause all old blank lines to be ignored, perhaps even some that were added by hand to improve formatting. So please be cautious when using these parameters. โš ๏ธ

bestie, this is the "irreversible formatting glow-up" of options. Read twice, run once. ๐Ÿ’…
  • -mbl=n, --maximum-consecutive-blank-lines=n โ€” this parameter specifies the maximum number of consecutive blank lines which will be output within code sections of a script. The default is n=1. If the input file has more than n consecutive blank lines, the number will be reduced to n โ€” except as noted above for the --blank-lines-before-subs and --blank-lines-before-subs parameters. (And yes, the manpage really does say --blank-lines-before-subs twice there. I'm just the messenger. ๐Ÿ’€) If n=0 then no blank lines will be output, unless all old blank lines are retained with the --keep-old-blank-lines=2 flag of the next section.

This flag obviously does not apply to pod sections, here-documents, and quotes. ๐Ÿšซ

  • -kbl=n, --keep-old-blank-lines=n โ€” the -kbl=n flag gives you control over how your existing blank lines are treated.

The possible values of n are:

n=0 ignore all old blank lines
n=1 stable: keep old blanks, but limited by the B<-mbl=n> flag
n=2 keep all old blank lines, regardless of the B<-mbl=n> flag

The default is n=1.

  • -sob, --swallow-optional-blank-lines โ€” this is equivalent to --keep-old-blank-lines=0 and is included for compatibility with previous versions.
  • -nsob, --noswallow-optional-blank-lines โ€” this is equivalent to --keep-old-blank-lines=1 and is included for compatibility with previous versions.

๐Ÿงฉ Controls for blank lines around lines of consecutive keywords ๐Ÿงฉ

The parameters in this section give you some control over the placement of blank lines within and around groups of statements beginning with selected keywords. These blank lines are called here keyword group blanks, and all of the parameters begin with --keyword-group-blanks*, or -kgb* for short. The default settings do not employ these controls, but they can be enabled with the following parameters:

  • -kgbl=s or --keyword-group-blanks-list=s โ€” s is a quoted string of keywords.
  • -kgbs=s or --keyword-group-blanks-size=s โ€” s gives the number of keywords required to form a group.
  • -kgbb=n or --keyword-group-blanks-before=n โ€” n = (0, 1, or 2) controls a leading blank.
  • -kgba=n or --keyword-group-blanks-after=n โ€” n = (0, 1, or 2) controls a trailing blank.
  • -kgbi or --keyword-group-blanks-inside โ€” a switch for adding blanks between subgroups.
  • -kgbd or --keyword-group-blanks-delete โ€” a switch for removing initial blank lines between keywords.
  • -kgbr=n or --keyword-group-blanks-repeat-count=n โ€” can limit the number of times this logic is applied.

In addition, these abbreviations are available for simplified usage:

  • -kgb or --keyword-group-blanks โ€” short for -kgbb=2 -kgba=2 kgbi
  • -nkgb or --nokeyword-group-blanks โ€” short for -kgbb=1 -kgba=1 nkgbi

Before describing the meaning of the parameters in detail, let us look at an example which is formatted with default parameter settings.

print "Entering test 2\n";
use Test;
use Encode qw(from_to encode decode
  encode_utf8 decode_utf8
  find_encoding is_utf8);
use charnames qw(greek);
my @encodings     = grep( /iso-?8859/, Encode::encodings() );
my @character_set = ( '0' .. '9', 'A' .. 'Z', 'a' .. 'z' );
my @source        = qw(ascii iso8859-1 cp1250);
my @destiny       = qw(cp1047 cp37 posix-bc);
my @ebcdic_sets   = qw(cp1047 cp37 posix-bc);
my $str           = join( '', map( chr($_), 0x20 .. 0x7E ) );
return unless ($str);

using perltidy -kgb gives:

           print "Entering test 2\n";
                                     <----------this blank controlled by -kgbb
           use Test;
           use Encode qw(from_to encode decode
             encode_utf8 decode_utf8
             find_encoding is_utf8);
           use charnames qw(greek);
                                     <---------this blank controlled by -kgbi
           my @encodings     = grep( /iso-?8859/, Encode::encodings() );
           my @character_set = ( '0' .. '9', 'A' .. 'Z', 'a' .. 'z' );
           my @source        = qw(ascii iso8859-1 cp1250);
           my @destiny       = qw(cp1047 cp37 posix-bc);
           my @ebcdic_sets   = qw(cp1047 cp37 posix-bc);
           my $str           = join( '', map( chr($_), 0x20 .. 0x7E ) );
                                     <----------this blank controlled by -kgba
           return unless ($str);

Okay so bestie, watch what just happened here ๐Ÿซถ โ€” blank lines got sprinkled around the my and use sequences. Why? Because the default keyword list has my and use in it but not print and return. So perltidy found a continuous sequence of nine my and use statements. Nine is way over the default threshold of five, so blanks went before and after the whole group. Then, because there was also a subsequence of six my lines chillin' inside, another blank line got inserted to split them apart. It's giving โœจstructuredโœจ.

But like, sometimes you want finer control over where the blanks land, and for that you use the individual parameters instead of the big -kgb flag. Here's the whole menu ๐Ÿ‘‡

  • -kgbl=s, --keyword-group-blanks-list=s โ€” where s is a quoted string, this defines the set of keywords that get formed into groups. The string is a space separated list of keywords. The default set is s="use require local our my", but honestly any list of keywords may be used. Comment lines may also be included in a keyword group, even though they are not keywords โ€” to include ordinary block comments, include the symbol BC. To include static block comments (which normally begin with '##'), include the symbol SBC. ๐Ÿ’…
  • -kgbs=s, --keyword-group-blanks-size=s โ€” where s is a string describing the number of consecutive keyword statements forming a group (Note: statements separated by blank lines in the input file are considered consecutive for purposes of this count). If s is an integer then it is the minimum number required for a group. A maximum value may also be given with the format s=min.max, where min is the minimum number and max is the maximum number, and the min and max values are separated by one or more dots. No groups will be found if the maximum is less than the minimum. The maximum is unlimited if not given. The default is s=5. Some examples, bestie:
s      min   max         number for group
3      3     unlimited   3 or more
1.1    1     1           1
1..3   1     3           1 to 3
1.0    1     0           (no match)

Ngl there is no really good default value for this parameter ๐Ÿ˜ญ If it is set too small, then an excessive number of blank lines may be generated. However, some users may prefer reducing the value somewhat below the default, perhaps to s=3.

  • -kgbb=n, --keyword-group-blanks-before=n โ€” specifies whether a blank should appear before the first line of the group, as follows:
n=0 => (delete) an existing blank line will be removed
n=1 => (stable) no change to the input file is made  [DEFAULT]
n=2 => (insert) a blank line is introduced if possible
  • -kgba=n, --keyword-group-blanks-after=n โ€” likewise specifies whether a blank should appear after the last line of the group, using the same scheme (0=delete, 1=stable, 2=insert). ๐ŸŽ€
  • -kgbi, --keyword-group-blanks-inside โ€” controls the insertion of blank lines between the first and last statement of the entire group. If there is a continuous run of a single statement type with more than the minimum threshold number (as specified with -kgbs=s) then this switch causes a blank line be inserted between this subgroup and the others. In the example above this happened between the use and my statements. ๐Ÿ‘‘
  • -kgbd, --keyword-group-blanks-delete โ€” controls the deletion of any blank lines that exist in the the group when it is first scanned. When statements are initially scanned, any existing blank lines are included in the collection. Any such original blank lines will be deleted before any other insertions are made when the parameter -kgbd is set. The default is not to do this, -nkgbd. ๐Ÿ˜ฌ
  • -kgbr=n, --keyword-group-blanks-repeat-count=n โ€” specifies n, the maximum number of times this logic will be applied to any file. The special value n=0 is the same as n=infinity which means it will be applied to an entire script [Default]. A value n=1 could be used to make it apply just one time for example. This might be useful for adjusting just the use statements in the top part of a module for example. ๐Ÿงš
  • -kgb, --keyword-group-blanks โ€” an abbreviation equivalent to setting -kgbb=1 -kgba=1 -kgbi. This turns on keyword group formatting with a set of default values.
  • -nkgb, --nokeyword-group-blanks โ€” equivalent to -kgbb=0 -kgba nkgbi. This flag turns off keyword group blank lines and is the default setting.

๐ŸŒธ some notes on how this technique actually works ๐ŸŒธ

  • These parameters are probably more useful as part of a major code reformatting operation rather than as a routine formatting operation.

In particular, note that deleting old blank lines with -kgbd is an irreversible operation so it should be applied with care ๐Ÿ˜ญ Existing blank lines may be serving an important role in controlling vertical alignment.

  • Conflicts which arise among these kgb* parameters and other blank line controls are generally resolved by producing the maximum number of blank lines implied by any parameter.

For example, if the flags --freeze-blank-lines, or --keep-old-blank-lines=2, are set, then they have priority over any blank line deletion implied by the -kgb flags of this section, so no blank lines will be deleted.

For another example, if a keyword group ends at a sub and the flag kgba=0 requests no blank line there, but we also have --blank-lines-before-subs=2, then two blank lines will still be introduced before the sub.

  • The introduction of blank lines does not occur if it would conflict with other input controls or code validity. For example, a blank line will not be placed within a here-doc or within a section of code marked with format skipping comments. And in general, a blank line will only be introduced at the end of a group if the next statement is a line of code. ๐Ÿ™ˆ
  • The count which is used to determine the group size is not the number of lines but rather the total number of keywords which are found. Individual statements with a certain leading keyword may continue on multiple lines, but if any of these lines is nested more than one level deep then that group will be ended.
  • The search for groups of lines with similar leading keywords is based on the input source, not the final formatted source. Consequently, if the source code is badly formatted, it would be best to make a first formatting pass without these options. ๐Ÿฉท

๐Ÿฆ‹ Styles ๐Ÿฆ‹

A style refers to a convenient collection of existing parameters. Like a little preset outfit, but for your code ๐Ÿ’…

๐ŸŒˆ -gnu, --gnu-style

-gnu gives an approximation to the GNU Coding Standards (which do not apply to perl, bestie, we know) as they are sometimes implemented. At present, this style overrides the default style with the following parameters:

-lp -bl -noll -pt=2 -bt=2 -sbt=2 -icp

To use this style with -xlp (--extended-line-up-parentheses) instead of -lp (--line-up-parentheses) use -gnu -xlp.

๐ŸŒธ -pbp, --perl-best-practices

-pbp is an abbreviation for the parameters in the book Perl Best Practices by Damian Conway:

-l=78 -i=4 -ci=4 -st -se -vt=2 -cti=0 -pt=1 -bt=1 -sbt=1 -bbt=1
-nsfs -nolq
-wbb="% + - * / x != == >= <= =~ !~ < > | & =
      **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x="

Please note that this parameter set includes -st (--standard-output) and -se (--standard-error-output) flags, which make perltidy act as a filter on one file only. These can be overridden by placing -nst and/or -nse after the -pbp parameter.

Also note that the value of continuation indentation, -ci=4, is equal to the value of the full indentation, -i=4. It is recommended that the either (1) the parameter -ci=2 be used instead, or (2) the flag -xci be set. This will help show structure, particularly when there are ternary statements. The following snippet illustrates these options. ๐Ÿ‘‡

# perltidy -pbp
$self->{_text} = (
     !$section        ? ''
    : $type eq 'item' ? "the $section entry"
    :                   "the section on $section"
    )
    . (
    $page
    ? ( $section ? ' in ' : '' ) . "the $page_ext manpage"
    : ' elsewhere in this document'
    );

# perltidy -pbp -ci=2
$self->{_text} = (
     !$section        ? ''
    : $type eq 'item' ? "the $section entry"
    :                   "the section on $section"
  )
  . (
    $page
    ? ( $section ? ' in ' : '' ) . "the $page_ext manpage"
    : ' elsewhere in this document'
  );

# perltidy -pbp -xci
$self->{_text} = (
     !$section        ? ''
    : $type eq 'item' ? "the $section entry"
    :                   "the section on $section"
    )
    . ( $page
        ? ( $section ? ' in ' : '' ) . "the $page_ext manpage"
        : ' elsewhere in this document'
    );

The -xci flag was developed after the -pbp parameters were published so you need to include it separately. ๐Ÿซถ


๐Ÿ’€ Making a file unreadable ๐Ÿ’€

The goal of perltidy is to improve the readability of files, but there are two commands which have the opposite effect, --mangle and --extrude. They are actually merely aliases for combinations of other parameters. Both of these strip all possible whitespace, but leave comments and pod documents, so that they are essentially reversible. The difference between these is that --mangle puts the fewest possible line breaks in a script while --extrude puts the maximum possible. Note that these options do not provided any meaningful obfuscation, because perltidy can be used to reformat the files. They were originally developed to help test the tokenization logic of perltidy, but they have other uses. One use for --mangle is the following:

perltidy --mangle myfile.pl -st | perltidy -o myfile.pl.new

This one's a lil remix ๐ŸŽ€ โ€” it makes the maximum possible number of one-line blocks (peep the next section for that), and sometimes it genuinely helps clean up a script that's formatted a whole mess.

You can do the same trick with --extrude instead of --mangle if you want the minimum number of one-line blocks instead.

And one more glow-up for --mangle: pair it with --delete-all-comments (-dac) and boom ๐Ÿ’ฅ, the file size of your perl script goes down.


๐ŸŒธ One-Line Blocks ๐ŸŒธ

Okay so a one-line block is a block of code where the stuff inside the curly braces is short enough to fit on a single line. Like:

if ( -e $file ) { print "'$file' exists\n" }

The other option โ€” a block that spans multiple lines โ€” is called a broken block. With a few exceptions, perltidy keeps the one-line blocks you already have (if it can do it and still respect the line-length limit), but it does not try to make new ones. Basically, perltidy follows your lead on broken vs. unbroken blocks. Respectful king ๐Ÿ‘‘.

The main exception, bestie, is this: perltidy will try to form new one-line blocks after the keywords map, eval, and sort, because those code blocks are usually tiny and just read way better on one line. You can control that behavior with the flag --one-line-block-exclusion-list listed down below โฌ‡๏ธ.

When you're using the cuddled-else style, the default handling of one-line blocks might beef with the cuddled style ๐Ÿ˜ค. If that happens, you can change the default with the flag --cuddled-break-option=n, which is described elsewhere.

Oh and when an existing one-line block is longer than the max line length and therefore has to get broken into multiple lines, perltidy checks for and adds any optional terminating semicolon โ€” unless you used -nasc โ€” as long as the block is a code block. โœจ

  • -olbxl=s, --one-line-block-exclusion-list=s โ€” like we said up top, perltidy will by default try to create new one-line blocks for certain block types. This flag lets you โœ‹ that for whichever block types you list in the string s. The list s can include any of the words "sort", "map", "grep", "eval", or it can be "*" to mean all of them. So say you want to stop multiline eval blocks from becoming one-line blocks โ€” you'd run -olbxl='eval'. In that case, existing one-line eval blocks stay on one line if they can, and existing multiline eval blocks stay multiline. No crossover episodes ๐Ÿšซ๐Ÿ“บ.
  • -olbn=n, --one-line-block-nesting=n โ€” nested one-line blocks are lines with code blocks that themselves contain code blocks. Like, this line right here is a nested one-line block:
         foreach (@list) { if ($_ eq $asked_for) { last } ++$found }

The default is to break lines like that into multiple lines, but you can control it with this flag. The values of n are:

n=0 break nested one-line blocks into multiple lines [DEFAULT]
n=1 stable: keep existing nested-one line blocks intact

So for that example up there, the default formatting (-olbn=0) gives you:

    foreach (@list) {
        if ( $_ eq $asked_for ) { last }
        ++$found;
    }

And if you pass -olbn=1, the line gets left alone if it's a single line in the source โ€” or broken into multiple lines if it was already broken into multiple lines in the source. It just mirrors whatever it walked in with ๐Ÿชž.

  • -olbs=n, --one-line-block-semicolons=n โ€” this flag handles where semicolons go at the end of one-line blocks. Semicolons are optional before a closing block brace, and honestly people omit them at the end of a one-line block that's just a single statement all the time. By default perltidy does whatever your input file did, but you can take the wheel with this flag. The values of n are:
n=0 remove terminal semicolons in single-statement one-line blocks
n=1 stable; keep input terminal semicolons [DEFAULT ]
n=2 add terminal semicolons in all one-line blocks

Heads up though ๐Ÿ‘€ โ€” the n=2 option does nothing if adding semicolons is prohibited with the -nasc flag. And also note that while n=2 adds missing semicolons to all one-line blocks no matter how complex, n=0 only removes ending semicolons that terminate one-line blocks containing just one semicolon. So these two are not exact inverses, no matter what your heart wants ๐Ÿ˜ญ.

Forming new one-line blocks ๐Ÿฆ‹

Sometimes you just want a script that has one-line blocks wherever humanly possible. There's no flag for it right now, but the workaround is cute and simple: run perltidy twice โ€” once with --noadd-newlines and then again with normal parameters, like this:

     cat infile | perltidy -nanl | perltidy >outfile

Feed it this snippet:

    if ( $? == -1 ) {
        die "failed to execute: $!\n";
    }
    if ( $? == -1 ) {
        print "Had enough.\n";
        die "failed to execute: $!\n";
    }

and you get:

    if ( $? == -1 ) { die "failed to execute: $!\n"; }
    if ( $? == -1 ) {
        print "Had enough.\n";
        die "failed to execute: $!\n";
    }

See that? Blocks with a single statement become one-line blocks. Slay ๐Ÿ’…

Breaking existing one-line blocks ๐Ÿ’”

There's no automatic way to break existing long one-line blocks into multiple lines, but you can still do it โ€” process a script, or a section of one, with a short value of the parameter maximum-line-length=n. Then when you reformat the script again with the normal parameters, the blocks that got broken stay broken (with the exceptions we already mentioned above).

Another trick for certain block types: format once with the --cuddled-else flag and --cuddled-break-option=2, then format again with normal parameters. That breaks any one-line blocks caught up in a cuddled-else style. Two-pass queen ๐Ÿ‘‘


๐ŸŽ€ Controlling Vertical Alignment ๐ŸŽ€

Vertical alignment is when you line up certain symbols across a list of consecutive similar lines so it's easier to read. Classic example โ€” the "fat commas" get aligned here:

        $data = $pkg->new(
            PeerAddr => join( ".", @port[ 0 .. 3 ] ),
            PeerPort => $port[4] * 256 + $port[5],
            Proto    => 'tcp'
        );

You can turn vertical alignment completely off with the -novalign flag mentioned below. But you can also force it to stop and restart by strategically dropping in blank lines. Like here, a blank line was added to keep the somewhat-similar things aligned together:

    %option_range = (
        'format'             => [ 'tidy', 'html', 'user' ],
        'output-line-ending' => [ 'dos',  'win',  'mac', 'unix' ],
        'character-encoding' => [ 'none', 'utf8' ],

        'block-brace-tightness'    => [ 0, 2 ],
        'brace-tightness'          => [ 0, 2 ],
        'paren-tightness'          => [ 0, 2 ],
        'square-bracket-tightness' => [ 0, 2 ],
    );

Here's the tea โ˜• on how it actually works: vertical alignment happens by locally increasing blank space that's already there, so it can line up with an adjacent line. It cannot happen if there's no blank space to grow. So if some existing control removed that space, no vertical alignment for you ๐Ÿ™ˆ. And conversely, if a control adds a space, then vertical alignment might happen. Balance, bestie.

Example:

        # perltidy -nwls='=>'
        $data = $pkg->new(
            PeerAddr=> join( ".", @port[ 0 .. 3 ] ),
            PeerPort=> $port[4] * 256 + $port[5],
            Proto=> 'tcp'
        );

Completely turning off vertical alignment with -novalign

The default is to use vertical alignment, but you can shut it all the way down with the -novalign flag.

If you want a lower level of control, there are three parameters: -vc, -vsc, and -vbc. These independently control alignment of code, side comments, and block comments. They're described in the next section โฌ‡๏ธ

Also, fun fact: -valign is literally just an alias for -vc -vsc -vbc, and its negative -novalign is an alias for -nvc -nvsc -nvbc. Same energy, different names ๐Ÿ’–

Controlling code alignment with --valign-code or -vc

The -vc flag turns on alignment of code symbols like =. The default is -vc. And if you want detailed control over which symbols get aligned, go look at the -valign-exclude-list parameter below.

Controlling side comment alignment with --valign-side-comments or -vsc

The -vsc flag turns on alignment of side comments, and it's enabled by default. If you disable side comment alignment with -nvsc, the comments show up at a fixed space from the code token before them. The default is -vsc.

Controlling block comment alignment with --valign-block-comments or -vbc

When -vbc is enabled, block comments can become aligned โ€” for example, if one comment in a consecutive sequence of comments gets outdented because it's longer than the max line length. When that happens, the whole group of comments stays aligned and gets outdented by the same amount. That coordinated alignment won't happen if -nvbc is set. The default is -vbc. Group chat cohesion, but make it comments ๐Ÿซถ

Finer alignment control with --valign-exclusion-list=s or -vxl=s and --valign-inclusion-list=s or -vil=s

You want even more granular control over alignment types? These two parameters have you. Most of the vertical alignments in typical programs happen at one of the tokens ',', '=', and '=>', but tons of other alignments are possible, and here's the full list:

  = **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x=
  { ( ? : , ; => && || ~~ !~~ =~ !~ // <=> -> q
  if unless and or err for foreach while until

These alignment types map to perl symbols, operators, and keywords โ€” except for 'q', which is the special case of alignment in a 'use' statement involving qw quotes and empty parens.

They're all enabled by default โœจ but you can selectively disable them by dropping one or more of these tokens into the space-separated list valign-exclusion-list=s. So for example, this would stop alignment at = and if:

  --valign-exclusion-list='= if'

If it's way easier to just say "hey, only these token types get aligned," then you flip it: put the types you wanna align into --valign-inclusion-list. When you do that, you can leave the valign-exclusion-list totally undefined, or just use the special symbol * for the exclusion list. So like, these params mean "only align at commas and fat commas":

 --valign-inclusion-list=', =>'
 --valign-exclusion-list='*'  ( this is optional and may be omitted )

These parameter lists are just space-separated tokens from that big list of possible alignment tokens we talked about, or a lone *. If you type a token nobody recognizes, bestie, it's just ignored โ€” no drama. And if the same token somehow ends up in both lists by accident, the exclusion list wins. Sorry, that's just the rules. ๐Ÿ’…

The default values of these parameters turn on every alignment ever, and they're equivalent to:

  --valign-exclusion-list=' '
  --valign-inclusion-list='*'

To make this make sense, look at this little snippet with default formatting:

 # perltidy
 $co_description = ($color) ? 'bold cyan'  : '';           # descr
 $co_prompt      = ($color) ? 'bold green' : '';           # prompt
 $co_unused      = ($color) ? 'on_green'   : 'reverse';    # unused

Now if we wanna exclude all alignments except the equals (so, include only equals), we'd do:

 # perltidy -vil='='
 $co_description = ($color) ? 'bold cyan' : '';          # descr
 $co_prompt      = ($color) ? 'bold green' : '';         # prompt
 $co_unused      = ($color) ? 'on_green' : 'reverse';    # unused

And if we wanted to exclude only the equals, it's:

 # perltidy -vxl='='
 $co_description = ($color) ? 'bold cyan' : '';     # descr
 $co_prompt = ($color) ? 'bold green' : '';         # prompt
 $co_unused = ($color) ? 'on_green' : 'reverse';    # unused

Ok so notice in that last one โ€” even though all we did was exclude the equals, the ternary alignments disappeared too. ๐Ÿ˜ญ Why? Because the vertical aligner sweeps from left to right and, like, usually just stops if an important alignment can't happen for whatever reason. It gives up, basically. It's giving "fine, I'll take my ball and go home."

But ALSO notice that the side comments stayed aligned, because their alignment is its own whole thing, controlled separately with --valign-side-comments (which we covered up above). ๐Ÿซถ


โœจ Aligning postfix unless and if with --valign-if-unless or -viu โœจ

By default, postfix if terms align, and postfix unless terms align, but they align separately โ€” they're not in the same group chat. Like this:

 # perltidy [DEFAULT]
 print "Tried to add: @Resolve\n" if ( @Resolve and !$Quiet );
 print "Would need: @DepList\n"   if ( @DepList and !$Quiet );
 print "Output:\n"                  unless $Quiet;
 print join( "\n", @Output ) . "\n" unless $Quiet;

The -viu flag makes a postfix unless get treated like it's a postfix if for alignment purposes, and so they all align together:

 # perltidy -viu
 print "Tried to add: @Resolve\n"   if ( @Resolve and !$Quiet );
 print "Would need: @DepList\n"     if ( @DepList and !$Quiet );
 print "Output:\n"                  unless $Quiet;
 print join( "\n", @Output ) . "\n" unless $Quiet;

โœจ Aligning signed numbers with --valign-signed-numbers or -vsn โœจ

Turning on -vsn makes columns of numbers that have both signed and unsigned values put the leading signs in their own little column. Obsessed. Example:

   # perltidy -vsn
   my @correct = (
       [  123456.79,   86753090000.868,  11 ],
       [ -123456.79,  -86753090000.868, -11 ],
       [  123456.001,  80.080,           10 ],
       [ -123456.001, -80.080,           0 ],
       [  10.9,        10.9,             11 ],
   );

The default is -vsn. You can turn it off to get strict left justification:

   # perltidy -nvsn
   my @correct = (
       [ 123456.79,   86753090000.868,  11 ],
       [ -123456.79,  -86753090000.868, -11 ],
       [ 123456.001,  80.080,           10 ],
       [ -123456.001, -80.080,          0 ],
       [ 10.9,        10.9,             11 ],
   );

Some points about -vsn, since it's got lore:

  • This option works by inserting a single space ahead of unsigned numbers when possible. It does not do that if it would mean increasing the maximum width of a column.
  • This option is mainly limited to lists of comma-separated numbers. For multiline lists of numbers, having trailing commas can sometimes improve the results. If they're missing, perltidy can add them โ€” for example with the parameters -wtc=b -atc. See "Adding and Deleting Commas".
  • This option has a control parameter --valign-signed-number-limit=N, or -vsnl=N. This value controls formatting of very long columns of numbers and should not normally need to be changed. To see what it's even for, imagine a very long column of just unsigned numbers โ€” say 1000 lines. If we add one single negative number, it'd be super annoying to shift all the other numbers over by one space. That would create a ton of file diffs but not actually look better when you're only looking at a local section of the table. The number N stops that from happening by not adding extra indentation to a run of more than N lines of unsigned numbers. The default value, N=20, is set to a number of lines where the ends of a long column of unsigned numbers aren't normally both in view anyway.

โœจ Aligning assignment operators with --valign-wide-equals or -vwe โœจ

These assignment operators are aligned independently by default:

  = **= += *= &= <<= &&= -= /= |= >>= ||= //= .= %= ^= x=

Setting --valign-wide-equals, or -vwe, makes them all get vertically aligned together, with the trailing = all lined up. For example, here's the default formatting for some code using several of these operators:

            $str .= SPACE x $total_pad_count;
            $str_len += $total_pad_count;
            $total_pad_count = 0;
            $str .= $rfields->[$j];
            $str_len += $rfield_lengths->[$j];

And here's that same code formatted with -vme:

            # perltidy -vme
            $str             .= SPACE x $total_pad_count;
            $str_len         += $total_pad_count;
            $total_pad_count  = 0;
            $str             .= $rfields->[$j];
            $str_len         += $rfield_lengths->[$j];

This option was added for issue git #135 and it can genuinely improve readability, but it's off by default so nobody's existing formatting gets wrecked. Respect. ๐Ÿซก


โœจ Extended Syntax โœจ

This section is all about the parameters for dealing with extended syntax.

For another method of handling extended syntax, go peek at the section "Skipping Selected Sections of Code".

Also, heads up: the module Perl::Tidy supplies a pre-filter and post-filter capability. That means calling the module from a separate program instead of going through the perltidy binary. iykyk.

  • -xs, --extended-syntax โ€” this flag lets perltidy handle certain common extensions to the standard syntax without complaining. For example, without this flag a structure like this would throw a syntax error:
     Method deposit( Num $amount) {
         $self->balance( $self->balance + $amount );
     }

This flag is enabled by default, but it can be deactivated with -nxs. Honestly, the probably-only reason to deactivate it is to generate more diagnostic messages when you're debugging a script.

  • -sal=s, --sub-alias-list=s โ€” this flag makes one or more words get treated exactly the same as if they were the keyword sub. The string s holds one or more alias words, separated by spaces or commas.

For example,

         perltidy -sal='method fun _sub M4'

will make perltidy treat the words 'method', 'fun', '_sub' and 'M4' the same as if they were 'sub'. Note that if the alias words are separated by spaces, then the string of words should be wrapped in quotes.

Also note that several other parameters accept a list of keywords, including 'sub' (see "Specifying Block Types"). You do not need to include any sub aliases in those lists. Just include the keyword 'sub' if you want, and all the aliases come along automatically. Bestie privileges. โœจ

  • -gal=s, --grep-alias-list=s โ€” this flag lets a code block following an external 'list operator' function get formatted as if it followed one of the built-in keywords grep, map or sort. The string s holds the names of one or more such list operators, separated by spaces or commas.

By 'list operator' we mean a function that gets invoked in the form

       word {BLOCK} @list

Perltidy tries to keep code blocks for these functions intact, since they're usually short, and it doesn't automatically break after the closing brace because a list might follow. It also does some special handling of continuation indentation.

For example, the code block arguments to the functions 'My_grep' and 'My_map' can be given formatting like 'grep' with

         perltidy -gal='My_grep My_map'

By default, these list operators in List::Util are automatically included:

       all any first none notall reduce reductions

Any operators you specify with --grep-alias-list get added to this list. And the next parameter can be used to remove words from this default list.

  • -gaxl=s, --grep-alias-exclusion-list=s โ€” the -gaxl=s flag is your method for removing any of the default list operators given above, by listing them in the string s. To remove all of the default operators, use -gaxl='*'.
  • -uf=s, --use-feature=s โ€” this flag tells perltidy to allow or disallow the syntax associated with a pragma in the string s. The current possible settings are:
    • --use-feature='class'. This tells perltidy to recognize the special words class, method, field, and ADJUST as defined for this feature.
    • --use-feature='noclass'. This tells perltidy not to treat the words class, method, field, ADJUST specially.
    • Neither of these (--use-feature not defined). This is the DEFAULT and the recommended setting. In this case perltidy will try to automatically handle both the newer --use-feature 'class' syntax and some conflicting uses of some of these special words by existing modules.
Okay bestie, tiny note before we keep going: this parameter is totally independent of any use feature control lines chilling inside a script. Perltidy does not go looking for them, doesn't read them, doesn't care. Why? Because perltidy has to be able to work on little bite-sized chunks of code sent over from an editor, so it literally cannot assume those control lines are gonna be inside the lines it's formatting. ๐Ÿ’…

Working around problems with older version of Perl ๐Ÿง“โœจ

Perltidy has a whole lil set of rules that help it dodge known subtleties and problems with older versions of perl, and ngl these rules always take priority over whatever formatting flags you set. Like, always always. For example, perltidy will usually avoid starting a new line with a bareword, because that could cause problems if use strict is active.

There is no way to override these rules. Periodt. ๐Ÿ™…โ€โ™€๏ธ


Deleting and Extracting Pod or Comments ๐Ÿ—‘๏ธ๐Ÿ“

Deleting selected text

Perltidy can selectively delete comments and/or pod documentation. Obsessed with the flexibility, fr fr.

  • -dac or --delete-all-comments โ€” this one deletes all comments and all pod documentation, leaving you with just code and any leading system control lines. So clean. So minimal. ๐Ÿ’€
  • -dp or --delete-pod โ€” this removes all pod documentation (but not comments).
  • Two commands that remove comments (but not pod) are: -dbc or --delete-block-comments and -dsc or --delete-side-comments. (Hanging side comments get deleted along with side comments here, just so you know.)

When side comments get deleted, any special control side comments for non-indenting braces will be retained, unless they've been deactivated with a -nnib flag.

The negatives of these commands also work, and those are the defaults. ๐Ÿซถ

When block comments are deleted, any leading 'hash-bang' will be retained. Also, if the -x flag is used, any system commands before a leading hash-bang will be retained (even if they're in the form of comments).

Writing selected text to a file

When perltidy writes a formatted text file, it has the ability to also send selected text to a file with a .TEE extension. And this text can include comments and pod documentation, bestie. Extracting content, we love to see it. โœจ

  • -tac or --tee-all-comments โ€” writes all comments and all pod documentation.
  • -tp or --tee-pod โ€” writes all pod documentation (but not comments).
  • The commands that write comments (but not pod) are: -tbc or --tee-block-comments and -tsc or --tee-side-comments. (Hanging side comments get written along with side comments here.)

The negatives of these commands also work, and are the defaults.


The perltidyrc file ๐ŸŽ€

Using a .perltidyrc command file

If you use perltidy frequently, you probably won't be happy until you create a .perltidyrc file so you stop typing the same commonly-used parameters over and over like a clown. ๐Ÿ˜ญ Perltidy will first look in your current directory for a command file named .perltidyrc. If it doesn't find one there, it keeps looking in other standard locations.

Those other locations are system-dependent, and you can see them with the command perltidy -dpro. Under Unix systems, it will first look for an environment variable PERLTIDY. Then it'll look for a .perltidyrc file in the home directory, and then for a system-wide file /usr/local/etc/perltidyrc, and then it'll look for /etc/perltidyrc. Note that these last two system-wide files do not have a leading dot. Further system-dependent info lives in the INSTALL file distributed with perltidy.

Under Windows, perltidy will also search for a configuration file named perltidy.ini, since Windows doesn't allow files with a leading period (.). Use perltidy -dpro to see the possible locations for your system. An example might be C:\Documents and Settings\All Users\perltidy.ini.

Another option is the use of the PERLTIDY environment variable. The method for setting environment variables depends on the version of Windows you're running, so check your vibe.

Under Windows NT / 2000 / XP the PERLTIDY environment variable can be placed in either the user section or the system section. The latter makes the configuration file common to all users on the machine. Be sure to enter the full path of the configuration file in the value of the environment variable. Ex. PERLTIDY=C:\Documents and Settings\perltidy.ini

The configuration file is free format โ€” it's just a list of parameters, exactly as you'd enter them on a command line. Any number of lines may be used, with any number of parameters per line, though it may be easiest to read with one parameter per line. Comment text begins with a #, and there must also be a space before the # for side comments. It's a good idea to put complex parameters in either single or double quotes.

Here's an example of a .perltidyrc file:

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

The parameters in the .perltidyrc file are installed first, so any parameters given on the command line will have priority over them. Command line stays winning. ๐Ÿ‘‘

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

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

There are several options that may be helpful in debugging a .perltidyrc file:

  • A very helpful command is --dump-profile or -dpro. It writes a list of all configuration filenames tested to standard output, and if a file is found, it dumps the content to standard output before exiting. So, to find out where perltidy looks for its configuration files, and which one (if any) it selects, just enter
perltidy -dpro
  • It may be simplest to develop and test configuration files with alternative names, and invoke them with -pro=filename on the command line. Then rename the desired file to .perltidyrc when finished.
  • The parameters in the .perltidyrc file can be switched off with the -npro option on the command line.
  • Any parameter in the .perltidyrc file can be overridden with a replacement value on the command line. This is because the command line is processed after the .perltidyrc file.
  • The commands --dump-options, --dump-defaults, --dump-long-names, and --dump-short-names, all described below, may all be helpful.

Skipping a line with an unknown parameter

Versions of perltidy greater than 20240511 have an option to filter unrecognized parameters from a perltidy command file. If a line in the file begins with three dashes followed by a parameter name (rather than one or two), then the line will be removed if the parameter is unknown. Otherwise, a dash will be removed to make the line valid. This option was added to allow a single command file to be used during the transition to a new version of perltidy. Honestly? Iconic forward-thinking behavior. ๐ŸŒˆ

Creating a new abbreviation

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

newword {
-opt1
-opt2
}

where newword is the abbreviation, and opt1, etc, are existing parameters or other abbreviations. The main syntax requirement is that the new abbreviation, along with its opening curly brace, must begin on a new line. Space before and after the curly braces is optional.

For a specific example, the following line

oneliner { --maximum-line-length=0 --noadd-newlines --noadd-terminal-newline}

or equivalently with abbreviations

oneliner { -l=0 -nanl -natnl }

could be placed in a .perltidyrc file to temporarily override the maximum line length with a large value, to temporarily prevent new line breaks from being added, and to prevent an extra newline character from being added to the file. All other settings in the .perltidyrc file still apply. Thus it provides a way to format a long 'one liner' when perltidy is invoked with

perltidy --oneliner ...

(Either -oneliner or --oneliner may be used). Cute, right? ๐ŸŽ€

Skipping leading non-perl commands with -x or --look-for-hash-bang

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

Please note: do not use this flag unless you're sure your script needs it. Parsing errors can occur if it doesn't have a hash-bang, or, for example, if the actual first hash-bang is in a here-doc. In that case a parsing error will occur because the tokenization will begin in the middle of the here-doc. ๐Ÿ˜ญ Consider yourself warned, bestie.

Debugging perltidy input ๐Ÿ•ต๏ธโ€โ™€๏ธโœจ

The --dump-... parameters

The following flags are available for debugging. Note that all commands named --dump-... will simply write some requested information to standard output and then immediately exit. No editing, no rewriting, just dump and dip. ๐Ÿ’…

  • --dump-cuddled-block-list or -dcbl โ€” dumps to standard output the internal hash of cuddled block types created by a --cuddled-block-list input string.
  • --dump-defaults or -ddf โ€” writes the default option set to standard output and quits.
  • --dump-integer-option-range or -dior โ€” writes a list of comma-separated values. Each line contains the name of an integer option along with its minimum, maximum, and default values.
  • --dump-profile or -dpro โ€” writes the name of the current configuration file and its contents to standard output and quits.
  • --dump-options or -dop โ€” writes the current option set to standard output and quits.
  • --dump-long-names, --dln โ€” spits out every command line long name (yk, the ones that get passed to Get_options) to standard output and then dips out. Bye. ๐Ÿ’จ
  • --dump-short-names, --dsn โ€” same energy, but it lists all the command line short names instead, then quits.
  • --dump-token-types, --dtt โ€” prints a whole list of every token type to standard output and quits. Yes queen, show us the tokens. ๐ŸŽ€
  • --dump-want-left-space, --dwls โ€” writes out the hash %want_left_space to standard output and quits. Peep the section on controlling whitespace around tokens if you're curious bestie.
  • --dump-want-right-space, --dwrs โ€” same vibe, other side: writes the hash %want_right_space to standard output and quits. Again, see the whitespace section.
There are more --dump- goodies waiting for you โ€” check "Analyzing Code" below. ๐Ÿฆ‹

  • --no-memoize, -nmem โ€” turns off memoizing. Lowkey memoization can cut run time when you're running perltidy over and over again in a single process. It's on by default, but you can kill it off for testing with -nmem.
  • --no-timestamp, -nts โ€” yeets any time stamps out of output files so that date differences don't make your test installation scripts absolutely lose it and fail. There's only a couple of spots where timestamps normally show up: one is in the headers of html files, and the other is when the -cscw option is selected. Default is to allow timestamps (--timestamp or -ts).
  • --file-size-order, -fso โ€” makes files get processed in order of increasing size when you're handling multiple files. This is so useful during program development when you're throwing huge numbers of differently-sized files at it, because it can reduce virtual memory usage. This is the default, and you can deactivate it with -nfso.
  • --maximum-file-size-mb=n, -maxfs=n โ€” sets the maximum file size, in megabytes, that perltidy will even attempt to format. This exists so you don't accidentally cause system problems by trying to format some gigantic data file. Most perl scripts are less than about 2 MB, fr. The integer n defaults to 10, so perltidy will skip formatting any file bigger than 10 MB. Say you wanna bump the limit to 20 MB, you'd do:
perltidy -maxfs=20
Heads up bestie, this length check has โœจrulesโœจ: it's applied to named files before they get read into memory. It's applied to files coming from standard input after they're read into memory. And it is not applied to character strings arriving by a call to the Perl::Tidy module. ๐Ÿ‘‘

โœจ Controls for when to stop processing โœจ

  • --maximum-level-errors=n, -maxle=n โ€” sets the max number of indentation level errors allowed before perltidy just gives up, skips formatting, and outputs the file verbatim. Default is n=1. Meaning: if the final indentation of a script differs from the starting indentation by more than 1 level, the file gets output verbatim. Want it to refuse to format if there are any indentation level errors? Use -maxle=0. Wanna skip this check entirely? Set n to a big number like n=100, or set n=-1.

For example, this little script has a level error of 3 and will be output verbatim:

Input and default output:
{{{

perltidy -maxle=100
{
    {
        {
  • --maximum-unexpected-errors=n, -maxue=n โ€” sets the max number of unexpected tokenization errors allowed before formatting is skipped and the script gets output verbatim. The whole point is to avoid accidentally formatting a non-perl script โ€” an html file, for instance. You can turn this check all the way off by setting n=0.

A recommended value is n=3. But the default is n=0 (aka skip this check) so it doesn't cause problems with scripts that have extended syntaxes. ๐Ÿ™ˆ

โœจ Handling errors in options which take integer values โœจ

A lot of the input parameters take integer values. Before processing starts, perltidy checks whether any of these integer parameters exceed their valid ranges. The default behavior when a range is exceeded is to write a warning message and reset the value to its default setting. You can change that default behavior with --integer-range-check=n, or -irc=n, like so:

n=0  skip check completely (for stress-testing perltidy only)
n=1  reset bad values to defaults but do not issue a warning
n=2  reset bad values to defaults and issue warning [DEFAULT]
n=3  stop if any values are out of bounds
The values n=0 and n=1 are mainly useful for testing purposes, iykyk. ๐Ÿ’…

โœจ Debugging perltidy tokenization โœจ

  • -DEBUG, -D โ€” writes a file with the extension .DEBUG for each input file, showing the tokenization of every single line of code. Fair warning: this can produce a lot of output ๐Ÿ˜ญ and is mainly useful for debugging tokenization issues during perltidy development.

๐Ÿ” Analyzing Code ๐Ÿ”

Perltidy already reports any obvious issues it finds during formatting โ€” unbalanced braces, the classics. But there's a whole set of parameters for making certain additional checks for issues that might be interesting to a programmer. These fall into two categories, based on their prefix: --dump- or --warn-:

  • The --dump- parameters read a file, write information to the standard output, and then exit without doing any formatting. Straight to the point, no notes.
  • The --warn- parameters, on the other hand, let perltidy function normally but issue warnings to the error output when certain conditions are encountered. Bestie is watching ๐Ÿ‘€

Some of these come with their own associated control parameters.

๐Ÿ’– Use --dump-block-summary to make a table of information on code blocks ๐Ÿ’–

You can build a table listing info about the blocks of code in a file with --dump-block-summary, or -dbs. This makes perltidy read and parse the file, write a table of comma-separated values for selected code blocks to standard output, and then exit. Important: this parameter must be on the command line, not in a .perlticyrc file, and it requires a single file name on the command line. For example:

perltidy -dbs somefile.pl >blocks.csv

That produces an output file blocks.csv whose lines hold these parameters:

filename     - name of the file
line         - line number of the opening brace of this block
line_count   - number of lines between opening and closing braces
code_lines   - number of lines excluding blanks, comments, and pod
type         - block type (sub, for, foreach, ...)
name         - block name if applicable (sub or asub name, label..)
depth        - nesting depth of the opening block brace
max_change   - change in depth to the most deeply nested code block
block_count  - total number of code blocks nested in this block
mccabe_count - McCabe complexity measure of this code block

This feature was built to help spot complex sections of code as an aid in refactoring. The McCabe complexity measure follows the definition used by Perl::Critic. By default the table contains these values for subroutines, but you can request them for any or all blocks of code or packages. For blocks that are loops nested within loops, a postfix + gets added to the "type" to flag possible code complexity. And even though the table doesn't otherwise say which blocks are nested inside other blocks, you can figure that out by computing and comparing the block ending line numbers. Iconic detective work. ๐Ÿ•ต๏ธโ€โ™€๏ธ

For subroutines, the number of call arguments (args) is listed in parentheses in the "type" column. So sub(9) means a sub with 9 args. Subroutines whose arg count can't easily be determined show up as sub(*). And heads up: the count includes any leading object passed in a method call (like $self).

By default the table lists subroutines with more than 20 "code_lines", but you can change that with these two parameters:

  • --dump-block-minimum-lines=n, or -dbl=n โ€” where n is the minimum number of "code_lines" to include. The default is -n=20. Note that "code_lines" means the number of lines excluding comments, blanks and pod.
  • --dump-block-types=s, or -dbt=s โ€” where the string s is a list of block types to include. A block's type is either the name of the perl builtin keyword for that block (like sub if elsif else for foreach ..) or the word immediately before the opening brace. There are also a few symbols for special block types, as follows:
if elsif else for foreach ... any keyword introducing a block
sub  - any sub or anonymous sub
asub - any anonymous sub
*    - any block except nameless blocks
+    - any nested inner block loop
package - any package or class
closure - any nameless block
elsif3  - an if-elsif- chain with 3 or more elsif's (see below)

A chain of if-elsif-... blocks can be reported as a single line item by entering the word elsif with an appended integer, as shown by that last item in the list. The integer indicates how many elsif blocks are required for a chain to get reported. If you use this, you might wanna also use -dbl=n with a smaller number of lines n than the default. Just saying. ๐Ÿซถ

Also, specific block loop types nested inside other loops can be selected by adding a + after the block name. (Nested loops are sometimes great little candidates for restructuring, ngl.)

The default is -dbt='sub'.

In these examples, a table block.csv gets created for a file somefile.pl:

  • This one selects both "subs" and "packages" that have 20 or more lines of code. Super useful in code containing multiple packages:
perltidy -dbs -dbt='sub package' somefile.pl >blocks.csv
  • This one selects block types sub for foreach while with 10 or more code lines:
perltidy -dbs -dbl=10 -dbt='sub for foreach while' somefile.pl >blocks.csv
  • This one selects blocks with 2 or more code lines that are type "sub" or are inner loops:
perltidy -dbs -dbl=2 -dbt='sub +' somefile.pl >blocks.csv
  • This one selects every block and package:
perltidy -dbs -dbl=1 -dbt='* closure' somefile.pl >blocks.csv
  • This one selects every if-chain containing 2 or more "elsif" blocks:
perltidy -dbs -dbl=1 -dbt='elsif2' somefile.pl >blocks.csv
  • And this one selects every "while" block with 6 or more code lines:
perltidy -dbs -dbt=while -dbl=6 somfile.pl >while.csv

Use --dump-unusual-variables to find unused, reused, and certain other variables of interest ๐Ÿ”

Okay bestie, so if you want the tea on your variables โ€” the ones that are sus, duplicated, or just kinda sitting there โ€” you use --dump-unusual-variables, aka -duv. This has to be on the command line, and you give it exactly one file name. It makes perltidy scan your file for certain variable types, dump whatever it finds to standard output, and then bounce immediately โ€” no formatting at all, it just exits. Periodt.

Like, for example:

perltidy -duv somefile.pl >vars.txt

and boom, you get a file where the lines look a lil something like:

1778:u: my $input_file
6089:r: my $j: reused - see line 6076

The values on each line are separated by colons, and here's what each one means ๐ŸŒธ:

  • line number โ€” the number of the line of the input file
  • issue โ€” a single letter telling you which issue it is (peep below for the deets)
  • variable name โ€” the name of the variable, preceded by a keyword
  • note โ€” an optional note referring to another line

If you've got a ton of issues, it's genuinely convenient to read that file into a spreadsheet. Just saying. Spreadsheet girlies stay winning ๐Ÿ’…

The checks are made for variables introduced by the keywords my, state, and our, plus variables defined with use vars and use constant. And highkey, you should also set use strict in your script so Perl itself can catch issues with variables that show up without any of those methods. Two vibes checking your work, no cap.

The types of checks are identified in the output with one of the letters r, s, p, u, and c, and here's the full rundown:

r: reused variable name

These are variables which are re-declared in the scope of a variable with the identical name. This can be confusing โ€” maybe not when the code is first written, but possibly later during maintenance work. For example, this can make it difficult to locate the correct variable with an editor when changes are being made. This issue can be avoided by renaming one of the conflicting variables. Note that this is similar to the Perl::Critic policy Variables::ProhibitReusedNames.

s: sigil change but reused bareword

These are variables which have the same bareword name but a different sigil ($, @, or %) as another variable in the same scope. For example, this occurs if variables $data and %data share the same scope. This can also be confusing for the reasons mentioned above and can be avoided by renaming one of the variables.

p: package-crossing variables

These are lexical variables which are declared in one package and still visible in subroutines of a different package in the same file. This can be confusing, and it might cause the program to run differently, or fail, if the the packages were ever split into separate files. This issue can usually be avoided by placing code in block braces of some type. For example, this issue is often found in test code and can sometimes be fixed by using the structure

main();

sub main { #<<<
## old main code goes here
}

The non-indenting-braces side comment "#<<<" is not required but will keep the indentation of the old code unchanged.

This check is only applied to package statements which are not enclosed in block braces in order avoid warnings at temporary package changes.

u: unused variables

These are lexical variables declared with "my" or "state" (but not "our") and not referenced again within their scope. Calling them unused is convenient but not really accurate; this is a "gray area" for a program. There are some good reasons for having such variables. For example, they might occur in a list of values provided by another routine or data structure, and therefore must be listed, even though they might not be referenced again. Having such variables can make them immediately available for future development and debugging, and can be beneficial for program clarity.

But sometimes they can occur due to being orphaned by a coding change, due to a misspelling, or by having an unintentional preceding "my". So it is worth reviewing them, especially for new code. Here is an example of an unused variable in a script located with this method:

BEGIN { my $string = "" }
...
$string .= "ok";

This looks nice at first glance, but the scope of the "my" declaration is limited to the surrounding braces, so it is not the same variable as the other $string and must therefore be reported as unused. This particular problem would have also been caught by perl if the author had used "strict".

c: unused constants

These are names which are declared with a "use constant" and a reference was not seen again within their package. They might be needed by an external package, or a set of standard definitions, or available for future development. And in some unusual cases a reference may have been missed by perltidy. But they might also be unused remnants from code development, or due to a misspelling, so it can be worthwhile reviewing them.

Exception: The following our variables are exempt from warnings: $VERSION, @EXPORT, @EXPORT_OK, %EXPORT_TAGS, @ISA, $AUTOLOAD.

Use --warn-variable-types to warn about certain variable types โš ๏ธ

The flag --warn-variable-types=string, or -wvt=string, is the --warn counterpart to --dump-unusual-variables, and can be used to produce a warning message if certain of the above variable types are encountered during formatting. All possible variable warnings may be requested with -wvt='*' or -wvt=1.

For example,

perltidy -wvt='*' somefile.pl

The default is not to do any of these checks, and it can also be indicated with -wvt=0.

To restrict the check to a specific set warnings, set the input string to be a space-separated or comma-separated list of the letters associated with the types of variables to be checked. For example:

perltidy -wvt='s r' somefile.pl

will process somefile.pl normally but issue a warning if either of the issues s or r, described above, are encountered.

A companion flag, --warn-variable-exclusion-list=string, or -wvxl=string, can be used to skip warning checks for a list of variable names. A leading and/or trailing '*' may be placed on any of these variable names to allow a partial match. ๐ŸŽ€

For example,

perltidy -wvt=1 -wvxl='$self $class *_unused'  somefile.pl

will do all possible checks but not report any warnings for variables $self, $class, and for example $value_unused.

This partial match option provides a way to trigger a warning message when a new unused variable is detected in a script. This can be accomplished by adding a unique suffix to the names of existing unused variables, such as "_unused". This suffix is then added to the exclusion list.

As a specific example, consider the following line which is part of some debug code which only references the latter three variables (but might someday need to reference the package variable too).

my ( $package_uu, $filename, $line, $subroutine ) = caller();

The unused variable, $package_uu, has been specially marked with suffix "_uu". No type u (unused variable) warning will be produced provided that this wildcard suffix is in the exclusion list:

-wvxl='*_uu'

Use --dump-unique-keys to help locate misspelled hash keys ๐Ÿ”‘

The parameter --dump-unique-keys, or -duk, dumps a list of hash keys which appear to be used just once, and do not appear among the quoted strings in a file. For example:

perltidy -duk File.pm >output.txt

The lines in the output file list each unique key and its line number. Typically, most of the listed keys listed will be perfectly valid keys needed, for example, for communication with other modules or for future development. But the list might also include something unexpected, such as a misspelled key. iykyk ๐Ÿ’€

A program "dump_unique_keys.pl" at https://github.com/perltidy/perltidy/tree/master/examples can run perltidy with -duk on multiple files, and then remove any common keys from the list.


Use --dump-mixed-call-parens to find functions called both with and without parens ๐Ÿซถ

The parameter --dump-mixed-call-parens, or -dmcp, provides information on the use of call parens within a program. It produces a list of keywords and sub names which occur both both with and without parens. In other words, with a mixed style. This might be useful if one is working to standardize the call style for some particular keyword or function. For example,

perltidy -dmcp somefile.pl >output.txt

will analyze the text of somefile.pl, write the results to output.txt, and then immediately exit (like all dump- parameters).

The output shows a list of operators and the number of times they were used with parens and the number of times without parens. For example, here is a small section of the output from one file in a past Perl distribution:

k:length:17:9
k:open:30:9
k:pop:3:4

The first line shows that the "length" function occurs 17 times with parens and 9 times without parens. The 'k' indicates that "length" is a Perl builtin keyword ('U' would mean user-defined sub, and 'w' would mean unknown bareword). So from this partial output we see that the author had a preference for parens around the args of "length" and "open", whereas "pop" was about equally likely to have parens as not. โœจ

More detailed information can be obtained with the parameters described in the next section.


Use --want-call-parens=s and --nowant-call-parens=s to warn about specific missing or extra call parens ๐Ÿ’…

The parameter --want-call-parens=s, or -wcp=s, can be used to to produce a warning message if call parens are missing from selected functions. Likewise, --nowant-call-parens=s, or -nwcp=s, can warn if call parens exist for selected functions. When either of these parameters are set, perltidy will report any discrepancies from the requested style in its error output.

Before you reach for either of those two parameters, lowkey do yourself a favor and run --dump-mixed-call-parens=s first (it's in the section right before this one) so you actually get a vibe check on how parens are already being used in the file. Saves you a whole meltdown later, bestie. ๐Ÿ’…

So the string arguments s are space-separated lists of function names you want checked. Those names can be builtin keywords or user-defined subs. They may not carry a package prefix or a sigil โ€” no exceptions, periodt. To make it make sense:

   perltidy -wcp='length open' -nwcp='pop'   somefile.pl

That means the builtin functions length and open should have parens wrapped around their call args, but pop should not. Iconic. Your error output might spit out lines like:

    2314:open FD_TO_CLOSE: no call parens
    3652:pop (: has call parens
    3783:length $DB: no call parens
    ...

For builtin keywords that rock both a block form and a trailing modifier form โ€” think if โ€” only the trailing modifier form gets checked, since parens are mandatory for the block form anyway. No point checking what's already required, yk?

The symbol & can be entered instead of a function name to mean all user-defined subs that aren't explicitly listed. So this tiny little expression:

  perltidy -wcp='&' somefile.pl

means every call to every user-defined sub in the file being processed should get its call arguments wrapped up in parens. Whole file, one vibe, no cap. โœจ

Perltidy does not have the ability to add or delete call parens, because it's genuinely difficult to automate. So you're making those changes manually, bestie. When you add or remove parentheses, it is essential that you pay attention to operator precedence issues. ๐Ÿšจ

For example, if the parens in the following statement are removed, then || must be changed to or:

    open( IN, "<", $infile ) || die("cannot open $infile:$!\n");

Otherwise, that || will operate on $infile rather than the return value of open. It's giving "silently wrong behavior" and we do not stan that. ๐Ÿ˜ญ


๐Ÿ•ต๏ธ Use --dump-mismatched-args to find function calls with args not matching sub declarations ๐Ÿ•ต๏ธ

The parameter --dump-mismatched-args, or -dma, makes perltidy examine the definitions of subroutines in a file and the calls to those subs, and then report certain differences. Like all --dump commands, it writes its report to standard output and exits immediately. For example:

    perltidy -dma somefile.pl >results.txt

Four types of issues get reported, types a, o, u, and i:

  • a: calls made to a sub both with and without the arrow operator. For example the following two lines would be reported as a mismatch:
    Fault();

and

    $self->Fault();

This may or may not be an error, but it is worth checking. It might become an error in the future if sub Fault starts to access $self.

  • o: (overcount): the number of call args exceeds the expected number.
  • u: (undercount): the number of call args is less than the expected number. For example:
    sub gnab_gib {
        my $self=shift;
        my ($v1,$v2)=@_;
        ...
    }

    $self->gnab_gib(42);

In this case, the sub is expecting a total of three args ($self, $v1, and $v2) but only receives two ($self and 42), so an undercount is reported. This is not necessarily an error because the sub may allow for this possibility, but it is worth checking.

Although it is not possible to automatically determine which sub args are optional, if optional sub args are enclosed in an extra set of parentheses, perltidy will take this as a signal that they are optional and not issue a warning. So if the above example is written as:

    sub gnab_gib {
        my $self = shift;
        my ( $v1, ($v2) ) = @_;  # <-- $v2 is optional
        ...;
    }

then perltidy will consider that the second arg is optional and not issue a warning for:

    $self->gnab_gib(42);

For multiple default call args, place one set of parens around them all. Some examples:

    my ( ($v1) ) = @_;              # <-- $v1 is optional
    my ( $v1, ( $v2, $v3 ) ) = @_;  # <-- $v2, $v3 are optional
  • i: indeterminate: a specific number of expected args for a sub could not be determined, but it is called with a specific number. This issue is reported for the --dump- option but not the --warn- option.

Notes and Limitations: ๐ŸŒธ

  • This option works best for subs which unpack call args in an orderly manner near the beginning of the sub from @_ and/or with shift operations. It will also work for direct access to specific elements of the @_ array. However if the coding for arg extraction is complex then the number of sub args will be considered indeterminate and a count cannot be checked.
  • Sub calls made without parentheses around the args are not checked.
  • Anonymous subs and lexical subs (introduced with my) are not checked.
  • Only calls which appear to be to subs defined within the file being processed are checked. But note that a file may contain multiple packages.

๐Ÿ’… Use --warn-mismatched-args to produce a warning for function calls with args not matching sub declarations ๐Ÿ’…

This is similar to the -dump parameter described above, except that any mismatches are reported in the error file and otherwise formatting continues normally. The basic usage is:

    perltidy -wma somefile.pl

Several companion controls are available to avoid unwanted error messages:

  • --warn-mismatched-arg-types=s, or -wmat=s โ€” can be used to select specific tests, type a (arrow test) or o (overcounts) or u (undercounts). All checks may be requested with -wmat='*' or -wmat=1. This is the default.

To restrict the check to a specific warning type, set the string equal to the letter of that warning, any a, o, or u. For example:

       perltidy -wmat='a o' somefile.pl

will format somefile.pl and report any arrow-type mismatches and overcount mismatches, but will skip undercount mismatches.

  • --warn-mismatched-arg-exclusion-list, or -wmaxl=string โ€” can be given to skip the warning checks for a list of subroutine names, entered as a quoted string of space- or comma-separated names, without a package prefix. All subs with those names will be skipped, regardless of package. A leading and/or trailing * on a name may be used to indicate a partial string match.
  • --warn-mismatched-arg-undercount-cutoff=n, or -wmauc=n โ€” can be used to avoid undercount warnings when the expected number of args is less than n. Please note that this number n is the number of args from the point of view of the sub definition, so an object like $self passed with an arrow operator counts as one arg.

The default value is n=4. This has been found to allow most programs to pass without warnings, but it should be reduced if possible for better error checking. The minimum possible value of n needed to avoid triggering an error for a program can be determined by running with -wma -wmauc=0. If there are undercount errors, a note at the bottom of the error output indicates the value of n required to avoid reporting them.

As noted above for the parameter --dump-mismatched-args, if optional call args are enclosed in separate parentheses, then perltidy will recognize them as optional args and avoid needless warnings. If this method is used, then -wmauc=0 should be used for maximal checking.

  • --warn-mismatched-arg-overcount-cutoff=n, or -wmaoc=n โ€” can be used to avoid overcount warnings when the expected number of args is less than n. The default value is n=1. This avoids warning messages for subroutines which are dummy placeholders for possible expansion.

To illustrate these controls:

    perltidy -wma -wmat='o u' -wmaxl='new old' -wmauc=2 somefile.pl

means format somefile.pl as usual and check for mismatched overcounts and undercounts but not arrows. Skip checking for any sub named new or old, and only warn of undercounts for subs expecting more than 2 args. Chef's kiss behavior tbh. ๐ŸŽ€


๐Ÿ”ฎ Use --dump-mismatched-returns to find function calls where the number of requested values may disagree with sub return statements ๐Ÿ”ฎ

The parameter --dump-mismatched-returns, or -dmr, examines the return side of sub call statements. Like all --dump commands, it writes its report to standard output and exits immediately. For example:

    perltidy -dmr somefile.pl >results.txt

The following types of issues are reported:

  • x: calls requesting an array from a sub with no return statements.
  • y: calls requesting a scalar from a sub with no return statements.
  • o: (overwant): calls requesting an array with a count which exceeds the maximum number returned by the sub.
  • u: (underwant): calls requesting an array with a count which is below the maximum and which does not match a number returned by the sub.
  • s: calls requesting a scalar from a sub which only returns two or more items.

These issue types are illustrated with the following code:

    sub macho {
        ...
        ( $name, $flags ); # 2 values but no 'return' statement
    }

    ( $name, $flags ) = macho();  # 'x' (want array, but no return)
    $name = macho();              # 'y' (want scalar but no return)

    sub wimp {
        ...;
        return ( $name, $flags );  # 2 values with 'return' statement
    }

    ( $name, $flags, $access) = wimp(); # 'o' (want array 3 > 2)
    ($name) = wimp();                   # 'u' (want array 1 < 2)
    $name   = wimp();  # 's' (want scalar but 2 values returned)

This analysis works by scanning all call statements and all sub return statements, and comparing the number of items wanted with the possible number of items returned. If a specific value for either of these numbers cannot be determined for a call then it cannot be checked. ๐Ÿคท

Okay so real talk bestie ๐Ÿ’– since only return statements get scanned for return values, this whole analysis situation is not gonna be useful for programming that relies on the default return mechanism โ€” yk, like the first sub up there โ˜๏ธ. But lowkey there's a save: the Perl::Critic policy RequireFinalReturn can be used to check for code in this exact situation, so you're not just out here vibing unprotected. ๐Ÿซถ

Also important: the issues it reports are not necessarily errors โ€” but they might be, or they might be flagging code that's just, like, confusing to read. So don't panic, just look. ๐Ÿ™ˆ

โœจ Use --warn-mismatched-returns to issue warnings when the number of requested values may disagree with sub return statements โœจ

This one is giving very much "same energy as -dump" (that parameter we talked about above ๐Ÿ‘†) except that any mismatches get reported in the error file, and formatting just keeps on keeping on like nothing happened. ๐Ÿ’… The basic usage is:

perltidy -wmr somefile.pl

And because nobody wants random โœจsurpriseโœจ error messages, there are these companion controls to keep things chill:

  • --warn-mismatched-return-types=string, or -wmrt=string โ€” bestie this is your limit-the-checks button. To restrict the checking, set the string equal to the letter(s) of that warning: any x, y, o, u, or s. For example:
perltidy -wmrt='x o s' somefile.pl

This will format somefile.pl and report issue types x, o, and s but not types u and y. ๐ŸŽ€ All checks may be requested with -wmrt='*' or -wmrt=1. This is the default. Slay.

  • --warn-mismatched-return-exclusion-list, or -wmrxl=string โ€” pass this in to skip the warning checks for a whole list of subroutine names ๐Ÿšซ. You enter it as a quoted string of space- or comma-separated names, without a package prefix. And heads up: all subs with those names will be skipped, regardless of package โ€” no cap. A leading and/or trailing * on a name may be used to indicate a partial string match. ๐Ÿฆ‹

๐ŸŽ€ Working with MakeMaker, AutoLoader and SelfLoader ๐ŸŽ€

Okay so first up: the first $VERSION line of a file which might be eval'd by MakeMaker is passed through unchanged except for indentation. The default --pass-version-line, or -pvl, is to do this. โœจ If you don't want that, use --nopass-version-line, or -npvl, to deactivate this feature.

Next: if the AutoLoader module is used, perltidy will continue formatting code after seeing an __END__ line. ๐Ÿ‘‘ The default --look-for-autoloader, or -lal, is to do this. Use --nolook-for-autoloader, or -nlal, to deactivate this feature.

And likewise ๐ŸŒธ if the SelfLoader module is used, perltidy will continue formatting code after seeing a __DATA__ line. The default --look-for-selfloader, or -lsl, is to do this. Use --nolook-for-selfloader, or -nlsl, to deactivate this feature. Periodt. ๐Ÿ’œ

๐ŸŒˆ HTML OPTIONS ๐ŸŒˆ

okay bestie, this is the โœจmake-it-pretty-in-a-browserโœจ chapter. Everything here is about turning your script into html, and honestly? it's giving art gallery. ๐ŸŽ€

โœจ The -html master switch โœจ

The flag -html makes perltidy write an html file with extension .html. So like, this command right here:

perltidy -html somefile.pl

will spit out a syntax-colored html file named somefile.pl.html that you can just open in a browser. Obsessed. ๐Ÿ’…

Please Note: In this case, perltidy does not do any formatting to the input file, and it does not write a formatted file with extension .tdy. Translation: two perltidy runs are required to create a fully reformatted, html copy of a script. Two runs, bestie. No skipping. ๐Ÿ˜ญ

๐Ÿ”ข The -pre flag for code snippets ๐Ÿ”ข

When the -pre flag is given, only the pre-formatted section, within the "<PRE>" and "</PRE>" tags, will be output. This keeps things lowkey simple when you wanna drop the output into other files. The default is to output a complete web page.

๐Ÿ”ข The -nnn flag for line numbering

When the -nnn flag is given, the output lines will be numbered. That's it. That's the whole thing. Numbered. โœจ

๐Ÿ“œ The -toc, or --html-table-of-contents flag ๐Ÿ“œ

By default, a table of contents to packages and subroutines will be written at the start of html output. Use -ntoc to prevent this. This might be useful, for example, for a pod document which contains a number of unrelated code snippets. Heads up though: this flag only influences the code table of contents โ€” it has no effect on any table of contents produced by pod2html (see the next item, we're getting there ๐Ÿซถ).

๐Ÿซง The -pod, or --pod2html flag ๐Ÿซง

So there are two options for formatting pod documentation:

The default is to pass the pod through the Pod::Html module (which forms the basis of the pod2html utility). Any code sections are formatted by perltidy, and the results then merged. Merging. Iconic behavior, honestly.

Note: perltidy creates a temporary file when Pod::Html is used; see "FILES". Also, Pod::Html creates temporary files for its cache. Just so you're not surprised by mystery files, bestie. ๐Ÿ™ˆ

NOTE: Perltidy counts the number of "=cut" lines, and either moves the pod text to the top of the html file if there is one "=cut", or leaves the pod text in its original order (interleaved with code) otherwise. One "=cut" = pod goes up top. More than that = pod stays interleaved with code. The way that it counts those linesโ€ฆ ๐Ÿ’…

Most of the flags accepted by pod2html may be included in the perltidy command line, and they will be passed to pod2html. In some cases, the flags have a prefix "pod" to emphasize that they are for the pod2html, and this prefix will be removed before they are passed to pod2html. The flags which have the additional "pod" prefix are:

--[no]podheader --[no]podindex --[no]podrecurse --[no]podquiet
--[no]podverbose --podflush

The flags which are unchanged from their use in pod2html are:

--backlink=s --cachedir=s --htmlroot=s --libpods=s --title=s
--podpath=s --podroot=s

where s is an appropriate character string. Careful though โ€” not all of these flags are available in older versions of Pod::Html. See your Pod::Html documentation for more information. ๐Ÿ“–

The alternative, indicated with -npod, is not to use Pod::Html, but rather to format pod text in italics (or whatever the stylesheet indicates), without special html markup. This is useful, for example, if pod is being used as an alternative way to write comments. Cute and functional. ๐ŸŒธ

๐Ÿ–ผ๏ธ The -frm, or --frames flag ๐Ÿ–ผ๏ธ

By default, a single html output file is produced. This can be changed with the -frm option, which creates a frame holding a table of contents in the left panel and the source code in the right side. This simplifies code browsing. Main character energy for real. ๐Ÿ‘‘

Assume, for example, that the input file is MyModule.pm. Then, for default file extension choices, these three files will be created:

MyModule.pm.html      - the frame
MyModule.pm.toc.html  - the table of contents
MyModule.pm.src.html  - the formatted source code

Obviously this file naming scheme requires that output be directed to a real file (as opposed to, say, standard output). If this is not the case, or if the file extension is unknown, the -frm option will be ignored. Rude of it, but okay. ๐Ÿ’€

๐ŸŽ€ The -text=s, or --html-toc-extension flag ๐ŸŽ€

Use this flag to specify the extra file extension of the table of contents file when html frames are used. The default is "toc". See "Specifying File Extensions".

๐Ÿงš The -sext=s, or --html-src-extension flag ๐Ÿงš

Use this flag to specify the extra file extension of the content file when html frames are used. The default is "src". See "Specifying File Extensions".

๐Ÿ’œ The -hent, or --html-entities flag ๐Ÿ’œ

This flag controls the use of Html::Entities for html formatting. By default, the module Html::Entities is used to encode special symbols. But ngl, this may not be the right thing for some browser/language combinations. Use --nohtml-entities or -nhent to prevent this. ๐Ÿซถ


๐ŸŒˆ Style Sheets ๐ŸŒˆ

Style sheets make it very convenient to control and adjust the appearance of html pages. The default behavior is to write a page of html with an embedded style sheet. Very self-sufficient of it. ๐Ÿ’…

An alternative to an embedded style sheet is to create a page with a link to an external style sheet. This is indicated with the -css=filename, where the external style sheet is filename. The external style sheet filename will be created if and only if it does not exist. This option is useful for controlling multiple pages from a single style sheet. Slay โ€” one stylesheet, many pages. ๐ŸŽ€

To cause perltidy to write a style sheet to standard output and exit, use the -ss, or --stylesheet, flag. This is useful if the style sheet could not be written for some reason, such as if the -pre flag was used. Thus, for example:

perltidy -html -ss >mystyle.css

will write a style sheet with the default properties to file mystyle.css. Chef's kiss. ๐Ÿ˜˜

The use of style sheets is encouraged ๐Ÿซถ, but a web page without a style sheets can be created with the flag -nss. Use this option if you must to be sure that older browsers (roughly speaking, versions prior to 4.0 of Netscape Navigator and Internet Explorer) can display the syntax-coloring of the html files. Vintage browser support, we love to see it. โญ


๐Ÿ’… Controlling HTML properties ๐Ÿ’…

Note: It is usually more convenient to accept the default properties and then edit the stylesheet which is produced. However, this section shows how to control the properties with flags to perltidy. Like, you can do it this way, but maybe don't, bestie. ๐Ÿ™ˆ

Syntax colors may be changed from their default values by flags of the either the long form, -html-color-xxxxxx=n, or more conveniently the short form, -hcx=n, where xxxxxx is one of the following words, and x is the corresponding abbreviation:

      Token Type             xxxxxx           x
      ----------             --------         --
      comment                comment          c
      number                 numeric          n
      identifier             identifier       i
      bareword, function     bareword         w
      keyword                keyword          k
      quote, pattern         quote            q
      here doc text          here-doc-text    h
      here doc target        here-doc-target  hh
      punctuation            punctuation      pu
      parentheses            paren            p
      structural braces      structure        s
      semicolon              semicolon        sc
      colon                  colon            co
      comma                  comma            cm
      label                  label            j
      sub definition name    subroutine       m
      pod text               pod-text         pd

A default set of colors has been defined, but they may be changed by providing values to any of the following parameters, where n is either a 6 digit hex RGB color value or an ascii name for a color, such as 'red'. ๐ŸŒˆ

To illustrate, the following command will produce an html file somefile.pl.html with "aqua" keywords:

perltidy -html -hck=00ffff somefile.pl

and this should be equivalent for most browsers:

perltidy -html -hck=aqua somefile.pl

Perltidy merely writes any non-hex names that it sees in the html file. The following 16 color names are defined in the HTML 3.2 standard:

black   => 000000,
silver  => c0c0c0,
gray    => 808080,
white   => ffffff,
maroon  => 800000,
red     => ff0000,
purple  => 800080,
fuchsia => ff00ff,
green   => 008000,
lime    => 00ff00,
olive   => 808000,
yellow  => ffff00
navy    => 000080,
blue    => 0000ff,
teal    => 008080,
aqua    => 00ffff,

Many more names are supported in specific browsers, but it is safest to use the hex codes for other colors. Helpful color tables can be located with an internet search for "HTML color tables". ๐Ÿ”

Besides color, two other character attributes may be set: bold, and italics. To set a token type to use bold, use the flag --html-bold-xxxxxx or -hbx, where xxxxxx or x are the long or short names from the above table. Conversely, to set a token type to NOT use bold, use --nohtml-bold-xxxxxx or -nhbx. Bold or not bold โ€” pick your fighter. ๐Ÿ’…

Likewise, to set a token type to use an italic font, use the flag --html-italic-xxxxxx or -hix, where again xxxxxx or x are the long or short names from the above table. And to set a token type to NOT use italics, use --nohtml-italic-xxxxxx or -nhix.

For example, to use bold braces and lime color, non-bold, italics keywords the following command would be used:

perltidy -html -hbs -hck=00FF00 -nhbk -hik somefile.pl

The background color can be specified with --html-color-background=n, or -hcbg=n for short, where n is a 6 character hex RGB value. The default color of text is the value given to punctuation, which is black as a default.

Here are some notes and hints:

  1. If you find a preferred set of these parameters, you may want to create a .perltidyrc file containing them. See the perltidy man page for an explanation.
  2. Rather than specifying values for these parameters, it is probably easier to accept the defaults and then edit a style sheet. The style sheet contains comments which should make this easy. ๐Ÿ‘‘
  3. The syntax-colored html files can be very large, so it may be best to split large files into smaller pieces to improve download times. ๐Ÿฆ‹

๐ŸŒˆ SOME COMMON INPUT CONVENTIONS ๐ŸŒˆ

๐Ÿงฉ Specifying Block Types

ok so bestie, here's the tea: a bunch of parameters out here refer to code block types, and you can customize them by also handing over an associated list of block types. ๐Ÿ“‹

The type of a block is literally just the name of the keyword that introduces it โ€” think if, else, or sub. โœจ

But here's the plot twist: a labeled block has no keyword at all, so you specify it with just a colon (:). And if you want all blocks? That's '*'. periodt. ๐Ÿ’…

Also important: the keyword sub means a named sub. For anonymous subs, you use the special keyword asub. iykyk ๐Ÿ‘‘

So for example, this parameter specifies sub, labels, BEGIN, and END blocks:

-cscl="sub : BEGIN END"

(yeah, the meaning of the -cscl parameter is described up above, go check it ๐Ÿซถ)

๐Ÿ’ก Note: those quotes around the list of block types are required because of the spaces, bestie. Don't skip 'em.

Another example โ€” this one specifies all block types for vertical tightness:

-bbvtl='*'

๐Ÿ“ Specifying File Extensions

Several parameters let you override the default file extensions. Like, a backup file extension can be specified with -bext=ext, where ext is whatever new extension you want. ๐ŸŒธ

Now, to give you some flexibility, there's a whole convention for deciding whether a leading . gets used. Here's how it works:

  • If the extension ext begins with A-Z, a-z, or 0-9 โ†’ it gets appended to the filename with an intermediate . (or maybe a _ on VMS systems, cute right?).
  • Otherwise โ†’ it gets appended directly, no dot. โœจ

Let's do examples, because examples slap. Say the file is somefile.pl:

  • -bext=old โ†’ a . is added, giving you somefile.pl.old ๐Ÿ’–
  • -bext=.old โ†’ no additional . is added, so again the backup file is somefile.pl.old ๐Ÿ˜Œ
  • -bext=~ โ†’ no dot is added, so the backup file will be somefile.pl~ ๐Ÿฆ‹

๐Ÿ”„ SWITCHES WHICH MAY BE NEGATED ๐Ÿ”„

okay so here's the full list of all short parameter names that let you slap a prefix 'n' on the front to get the negated form:

 D      aia    altc   ame    anl    asbl   asc    ast    asu    atc
 atnl   aws    b      baa    baao   bar    bbao   bbb    bbc    bbs
 bl     bli    boa    boc    bok    bol    bom    bos    bot    cblx
 ce     conv   cpb    cs     csc    cscb   cscw   dac    dbc    dbs
 dcbl   dcsc   ddf    dia    dior   dln    dltc   dma    dmcp   dmr
 dnl    dop    dp     dpro   drc    dsc    dsm    dsn    dtc    dtco
 dtt    duk    duv    dwic   dwls   dwrs   dws    eos    f      fpva
 frm    fs     fso    gcs    hbc    hbcm   hbco   hbh    hbhh   hbi
 hbj    hbk    hbm    hbn    hbp    hbpd   hbpu   hbq    hbs    hbsc
 hbv    hbw    hent   hic    hicm   hico   hih    hihh   hii    hij
 hik    him    hin    hip    hipd   hipu   hiq    his    hisc   hiv
 hiw    hsc    html   ibc    icb    icp    ils    iob    ipc    isbc
 iscl   kgb    kgbd   kgbi   kis    lal    log    lop    lp     lsl
 mci    mem    nib    ohbr   okw    ola    olc    oll    olq    opr
 opt    osbc   osbr   otr    ple    pod    pvl    q      qwaf   sac
 sbc    sbl    scbb   schb   scp    scsb   sct    se     sfp    sfs
 skp    sob    sobb   sohb   sop    sosb   sot    ssc    st     sts
 t      tac    tbc    toc    tp     tqw    trp    ts     tsc    tso
 vbc    vc     viu    vmll   vsc    vsn    vwe    w      wfc    wia
 wma    wme    wmr    wn     x      xbt    xci    xlp    xs

And equivalently (same energy, longer name), you can use the prefix 'no' or 'no-' on the corresponding long names instead. ๐Ÿ’œ


โš ๏ธ LIMITATIONS โš ๏ธ

๐Ÿง  Parsing Limitations

Perltidy should work properly on most perl scripts. It does a lot of self-checking, but still โ€” it is possible that an error could be introduced and go undetected. ๐Ÿ˜ญ

So it is essential to make careful backups and to test reformatted scripts. Like, for real for real. No cap.

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

If you encounter a bug, please report it. ๐Ÿซถ

๐Ÿšซ What perltidy does not parse and format

ok bestie, let's be clear about the boundaries here:

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

๐Ÿ“‚ FILES ๐Ÿ“‚

๐Ÿ—‚๏ธ Temporary files

Under the -html option with the default --pod2html flag, a temporary file is required to pass text to Pod::Html. Unix systems will try to use the POSIX tmpnam() function. Otherwise the file perltidy.TMP will be temporarily created in the current working directory. โœจ

๐Ÿงต Special files when standard input is used

When standard input is used, the log file โ€” if saved โ€” is perltidy.LOG, and any errors are written to perltidy.ERR unless the -se flag is set. These are saved in the current working directory. ๐ŸŒธ

๐Ÿ’ฅ Files overwritten

The following file extensions are used by perltidy, and files with these extensions may be overwritten or deleted: .ERR, .LOG, .TEE, and/or .tdy, .html, and .bak, depending on the run type and settings. ๐Ÿ˜ณ

๐Ÿšง Files extensions limitations

Perltidy does not operate on files for which the run could produce a file with a duplicated file extension. These extensions include .LOG, .ERR, .TEE, and perhaps .tdy and .bak, depending on the run type.

The purpose of this rule is to prevent generating confusing filenames such as somefile.tdy.tdy.tdy. ๐Ÿ’€ yeah. nobody wants that.


๐Ÿšจ ERROR HANDLING ๐Ÿšจ

An exit value of 0, 1, or 2 is returned by perltidy to indicate the status of the result.

  • An exit value of 0 indicates that perltidy ran to completion with no error messages. ๐ŸŽ‰ slay!
  • A non-zero exit value indicates some kind of problem was detected.
  • An exit value of 1 indicates that perltidy terminated prematurely, usually due to some kind of errors in the input parameters. This can happen for example if a parameter is misspelled or given an invalid value. Error messages in the standard error output will indicate the cause of any problem. If perltidy terminates prematurely then no output files will be produced. ๐Ÿ’€
  • An exit value of 2 indicates that perltidy was able to run to completion but there there are (1) warning messages in the standard error output related to parameter errors or problems and/or (2) warning messages in the perltidy error file(s) relating to possible syntax errors in one or more of the source script(s) being tidied. When multiple files are being processed, an error detected in any single file will produce this type of exit condition. ๐Ÿ˜ญ
(yes, the original really does say "there there" twice, we're keeping it, it's iconic)

๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

perlstyle(1), Perl::Tidy(3)


๐Ÿ› ๏ธ INSTALLATION ๐Ÿ› ๏ธ

The perltidy binary uses the Perl::Tidy module and is installed when that module is installed. The module name is case-sensitive, bestie. Don't play with it. ๐Ÿ’…

For example, the basic command for installing with cpanm is:

cpanm Perl::Tidy

โญ VERSION โญ

This man page documents perltidy version 20250105


๐Ÿ› BUG REPORTS ๐Ÿ›

The source code repository is at <https://github.com/perltidy/perltidy>.

To report a new bug or problem, use the "issues" link on this page. ๐Ÿซถ


Copyright (c) 2000-2025 by Steve Hancock


๐Ÿ“œ LICENSE ๐Ÿ“œ

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

Please refer to the file "COPYING" for details.


๐Ÿ™ˆ DISCLAIMER ๐Ÿ™ˆ

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

See the "GNU General Public License" for more details.


and that's a wrap on the whole man page, bestie!! ๐ŸŽ€ this one is PERLTIDY(1p) from perl v5.40.1, dated 2026-01-27 โ€” go forth and tidy those scripts, you absolute icon ๐Ÿ‘‘โœจ๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from