Perl Beautifier

Re-indent Perl code by block depth.

0 chars
0 words
0 lines
0 chars
0 words
0 lines

Perl Beautifier – Re-indent Perl Scripts

Perl scripts that have been edited by many people, copied from emails, or written in a hurry often have inconsistent indentation. The Perl beautifier re-indents your code according to its block structure, so every sub, if, foreach, and hash definition sits at the right depth.

How it works

The beautifier reads the script line by line and tracks the nesting of braces, parentheses, and brackets — while skipping over everything that can contain those characters without opening a block:

  • Single-quoted, double-quoted, and backtick strings, including strings that span lines.
  • Quote-like operators: q(), qq{}, qw[], qr//, m{}, s///, tr///, and y///.
  • Regular expressions after =~ and !~.
  • Comments starting with # (but not $#array).
  • Heredocs (<<EOT, <<"EOT", <<'EOT', <<~EOT) – their content is kept byte for byte.
  • POD documentation blocks (=pod … =cut) and everything after __END__ or __DATA__.

Each line is then indented by its depth, lines starting with a closing brace are outdented, trailing whitespace is removed, and runs of blank lines are collapsed into one.

Options

Choose 4 spaces (the perlstyle recommendation), 2 spaces, or tabs.

What it does not do

This is a re-indenter, not a full reformatter like Perl::Tidy. It does not add spaces around operators, break long lines, or change your code in any other way — which also means it can never change what your script does. If you need full reformatting, run perltidy locally after re-indenting.

Test regular expressions with a regex tool, format SQL embedded in DBI calls with the SQL Beautifier, or clean up JSON produced by your scripts with the JSON Beautifier.

Frequently Asked Questions

No. Perl::Tidy is a full Perl formatter. This tool only re-indents lines based on block structure, which is safe for any script and does not require a Perl installation.

No. Heredoc bodies, POD blocks, and the __END__/__DATA__ section are copied exactly as written.

Perl's syntax is famously hard to parse without running Perl. Unusual constructs, such as a regex with an unbalanced brace that is not preceded by =~, can confuse the brace counter. Such cases are rare; adjust the line manually.