The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

Perltidy Style Key

Use this document to quickly and methodically find a set of perltidy parameters to approximate your style. Just read each question and select the best answer. Enter your parameters in a file named .perltidyrc (examples are listed at the end). Then move it to one of the places where perltidy will find it. You can run perltidy with the parameter -dpro to see where these places are for your system.

Before you begin, experiment using just perltidy filename.pl on some of your files. From the results (which you will find in files with a .tdy extension), you will get a sense of what formatting changes, if any, you'd like to make. If the default formatting is acceptable, you do not need a .perltidyrc file.

Use as Filter?

Do you almost always want to run perltidy as a standard filter on just one input file? If yes, use -st and -se.

Line Length Setting

Perltidy will set line breaks to prevent lines from exceeding the maximum line length.

Do you want the maximum line length to be 80 columns? If no, use -l=n, where n is the number of columns you prefer.

Indentation in Code Blocks

In the block below, the variable $anchor is one indentation level deep and is indented by 4 spaces as shown here:

    if ( $flag eq "a" ) {
        $anchor = $header;
    }  

If you want to change this to be a different number n of spaces per indentation level, use -i=n.

Continuation Indentation

Look at the statement beginning with $anchor:

    if ( $flag eq "a" ) {
        $anchor =
          substr( $header, 0, 6 )
          . substr( $char_list, $place_1, 1 )
          . substr( $char_list, $place_2, 1 );
    }

The statement is too long for the line length (80 characters by default), so it has been broken into 4 lines. The second and later lines have some extra "continuation indentation" to help make the start of the statement easy to find. The default number of extra spaces is 2. If you prefer a number n different from 2, you may specify this with -ci=n. It is best to keep this less than the value of the primary indentation.

Tabs

The default, and recommendation, is to represent leading whitespace with actual space characters. However, if you prefer to entab leading whitespace with one tab character for each n spaces, use -et=n. Typically, n would be 8.

Opening Block Brace Right or Left?

Decide which of the following opening brace styles you prefer:

If you like opening braces on the right, like this, go to "Braces Right".

    if ( $flag eq "h" ) {
        $headers = 0;
    }  

If you like opening braces on the left, like this, go to "Braces Left".

    if ( $flag eq "h" )
    {
        $headers = 0;
    }

Braces Right

In a multi-line if test expression, the default is to place the opening brace on the left, like this:

    if ( $bigwasteofspace1 && $bigwasteofspace2
        || $bigwasteofspace3 && $bigwasteofspace4 )
    {
        big_waste_of_time();
    }

This helps to visually separate the block contents from the test expression.

An alternative is to keep the brace on the right even for multiple-line test expressions, like this:

    if ( $bigwasteofspace1 && $bigwasteofspace2
        || $bigwasteofspace3 && $bigwasteofspace4 ) {
        big_waste_of_time();
    }

If you prefer this alternative, use -bar.

Cuddled Else?

Do you prefer this Cuddled Else style

    if ( $flag eq "h" ) {
        $headers = 0;
    } elsif ( $flag eq "f" ) {
        $sectiontype = 3;
    } else {
        print "invalid option: " . substr( $arg, $i, 1 ) . "\n";
        dohelp();
    }

instead of this default style?

    if ( $flag eq "h" ) {
        $headers = 0;
    }  
    elsif ( $flag eq "f" ) {
        $sectiontype = 3;
    } 
    else {    
        print "invalid option: " . substr( $arg, $i, 1 ) . "\n";
        dohelp();
    }

If yes, you should use -ce.

Now skip ahead to "Indentation Style for Other Containers".

Braces Left

Use -bl if you prefer this style:

    if ( $flag eq "h" )
    {
        $headers = 0;
    }

Use -bli if you prefer this indented-brace style:

    if ( $flag eq "h" )
      {
        $headers = 0;
      }

The number of spaces of extra indentation will be the value specified for continuation indentation with the -ci=n parameter (2 by default).

Block Brace Vertical Tightness

The default is to leave the opening brace on a line by itself, like this (shown for -bli, but also true to -bl):

    if ( $flag eq "h" )
      {
        $headers = 0;
      }

But you may also use this more compressed style if you wish:

    if ( $flag eq "h" )
      { $headers = 0;
      }

If you do not prefer this more compressed form, go to "Indentation Style for Other Containers".

Otherwise use parameter -bbvt=n, where n=1 or n=2. To decide, look at this snippet:

    # -bli -bbvt=1
    sub _directives
      {
        {
            'ENDIF' => \&_endif,
               'IF' => \&_if,
        };
      }

    # -bli -bbvt=2
    sub _directives
      { {
            'ENDIF' => \&_endif,
               'IF' => \&_if,
        };
      }

The difference is that -bbvt=1 breaks after an opening brace if the next line is unbalanced, whereas -bbvt=2 never breaks.

Indentation Style for Other Containers

You have a choice of two indentation schemes for non-block containers. The default is to use a fixed number of spaces per indentation level (the same number of spaces used for code blocks). Here is an example of the default:

    $dbh = DBI->connect(
        undef, undef, undef,
        {
            PrintError => 0,
            RaiseError => 1
        }
    );

The alternate is to let the location of the opening paren (or square bracket, or curly brace) define the indentation, like this:

    $dbh = DBI->connect(
                         undef, undef, undef,
                         {
                           PrintError => 0,
                           RaiseError => 1
                         }
    );

If you prefer the first (default) scheme, skip ahead to "Closing Token Placement".

If you prefer the latter scheme, use -lp and continue to the next section.

Opening Vertical Tightness

The default -lp indentation style ends a line at the opening tokens, like this:

    $dbh = DBI->connect(
                         undef, undef, undef,
                         {
                           PrintError => 0,
                           RaiseError => 1
                         }
    );

Here is a tighter alternative, which does not end a line with the opening tokens:

    $dbh = DBI->connect( undef, undef, undef,
                         { PrintError => 0,
                           RaiseError => 1
                         }
    );

If you prefer the default, skip ahead to "Closing Token Placement".

Otherwise, use -vt=n, where n should be either 1 or 2. To help decide, observe the first three opening parens in the following snippet and choose the value of n you prefer. Here it is with -lp -vt=1:

    if (
         !defined(
                   start_slip( $DEVICE, $PHONE,  $ACCOUNT, $PASSWORD,
                               $LOCAL,  $REMOTE, $NETMASK, $MTU
                   )
         )
         && $continuation_flag
      )
    {
        do_something_about_it();
    }

And here it is again formatted with -lp -vt=2:

    if ( !defined( start_slip( $DEVICE, $PHONE,  $ACCOUNT, $PASSWORD,
                               $LOCAL,  $REMOTE, $NETMASK, $MTU
                   )
         )
         && $continuation_flag
      )
    {
        do_something_about_it();
    }

The -vt=1 style tries to display the structure by preventing more than one step in indentation per line. In this example, the first two opening parens were not followed by balanced lines, so -vt=1 broke after them.

The -vt=2 style does not limit itself to a single indentation step per line.

Closing Token Placement

You have several options for dealing with the terminal closing tokens of non-blocks. In the following examples, a closing parenthesis is shown, but these parameters apply to closing square brackets and curly braces as well. Also, the following examples show the default indentation, but they apply for -lp indentation as well.

The default is to put a closing paren on a separate line, with the indentation defined by the next (lower) indentation level, like this:

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

Skip ahead to "Define Horizontal Tightness" if you like this.

A slight variation is to place it on a separate line but leave it indented with the previous indentation level, like this:

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

Use -icp if you prefer this and skip ahead to "Define Horizontal Tightness".

Finally, the question of paren indentation can be avoided by placing it at the end of the previous line, like this:

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

Use -vtc=n if you prefer to do this, where n is either 1 or 2. To determine n, we have to look at something more complex. Observe the behavior of the closing tokens in the following snippet:

Here is -lp -vtc=1:

    $srec->{'ACTION'} = [
                          $self->read_value(
                                             $lookup->{'VFMT'},
                                             $loc, $lookup, $fh
                          ),
                          $self->read_value(
                                             $lookup->{'VFMT2'},
                                             $loc, $lookup, $fh
                          ) ];

Here is -lp -vtc=2:

    $srec->{'ACTION'} = [
                          $self->read_value(
                                             $lookup->{'VFMT'},
                                             $loc, $lookup, $fh ),
                          $self->read_value(
                                             $lookup->{'VFMT2'},
                                             $loc, $lookup, $fh ) ];
 

Choose the one that you prefer. The difference is that -vtc=1 leaves closing tokens at the start of a line within a list, which can assist in keeping hierarchical lists readable. The -vtc=2 style always tries to move closing tokens to the end of a line.

Define Horizontal Tightness

Horizontal tightness parameters define how much space is included within a set of container tokens.

For parentheses, decide which of the following values of -pt=n you prefer:

 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

For n=0, space is always used, and for n=2, space is never used. For the default n=1, space is used if the parentheses contain more than one token.

For square brackets, decide which of the following values of -sbt=n you prefer:

 $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 

For curly braces, decide which of the following values of -bt=n you prefer:

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

For code block curly braces, decide which of the following values of -bbt=n you prefer:

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

Statement Termination Semicolon Spaces

The default is not to put a space before a statement termination semicolon, like this:

    $i = 1;

If you prefer a space, like this:

        $i = 1 ; 

enter -sts.

For Loop Semicolon Spaces

The default is to place a space before a semicolon in a for statement, like this:

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

If you prefer no such space, like this:

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

enter -nsfs.

Block Comment Indentation

Block comments are comments which occupy a full line, as opposed to side comments. The default is to indent block comments with the same indentation as the code block that contains them (even though this will allow long comments to exceed the maximum line length).

If you would like block comments indented except when this would cause the maximum line length to be exceeded, use -olc. This will cause a group of consecutive block comments to be outdented by the amount needed to prevent any one from exceeding the maximum line length.

If you never want block comments indented, use -nibc.

If block comments may only be indented if they have some space characters before the leading # character in the input file, use -isbc.

Outdenting Long Quotes

Long quoted strings may exceed the specified line length limit. The default, when this happens, is to outdent them to the first column. Here is an example of an outdented long quote:

        if ($source_stream) {
            if ( @ARGV > 0 ) {
                die
 "You may not specify any filenames when a source array is given\n";
            }
        }

The effect is not too different from using a here document to represent the quote. If you prefer to leave the quote indented, like this:

        if ($source_stream) {
            if ( @ARGV > 0 ) {
                die
                  "You may not specify any filenames when a source array is given\n";
            }
        }

use -nolq.

Example .perltidyrc files

Now gather together all of the parameters you prefer and enter them in a file called .perltidyrc.

Here are some example .perltidyrc files and the corresponding style.

Here is a little test snippet, shown the way it would appear with the default style.

    for (@methods) {
        push (
            @results,
            {
                name => $_->name,
                help => $_->help,
            }
        );
    }

You do not need a .perltidyrc file for this style.

Here is the same snippet

    for (@methods)
    {
        push (@results,
              { name => $_->name,
                help => $_->help,
              }
        );
    }

for a .perltidyrc file containing these parameters:

 -bl
 -lp
 -vt=1
 -pt=2

You do not need to place just one parameter per line, but this may be convenient for long lists. You may then hide any parameter by placing a # symbol before it.

And here is the snippet

    for (@methods) {
        push ( @results,
               { name => $_->name,
                 help => $_->help,
               } );
    }

for a .perltidyrc file containing these parameters:

 -lp
 -vt=1
 -vtc=1

Additional Information

This document has covered the main parameters. Many more parameters are available for special purposes and for fine-tuning a style. For complete information see the perltidy manual http://perltidy.sourceforge.net/perltidy.html

For an introduction to using perltidy, see the tutorial http://perltidy.sourceforge.net/tutorial.html

Suggestions for improving this document are welcome and may be sent to perltidy at users.sourceforge.net