Perl Beautifier

Re-indent a Perl script from its block structure without disturbing sigils, regular expressions or POD sections.

Perl source
Formatted Perl
Runs locally in your browser

About the Perl Beautifier

Perl is famously hard to parse without running it, so this beautifier does the one job it can do safely: it fixes leading whitespace. Line breaks are kept exactly as you wrote them by default, because deciding where a Perl statement ends requires knowing whether a slash is a division sign or the start of a match, and no scanner can settle that reliably.

What it does know: # starts a comment except when it follows a dollar sign, so $#array is safe. Single and double quoted strings are read as units with backslash escapes honoured. POD sections that begin with an equals sign in column one and run to =cut are copied out untouched, documentation formatting and all.

Indentation comes from counting braces, brackets and parentheses per line, then printing a line that starts with a closer one level out. Since the counting is balanced within each line, a hash subscript like $tally{$key} or a slice such as @list[0..3] has no effect on depth. Subs, while and foreach blocks, and nested data structures all step in and out correctly.

The known weak spot is a regular expression that contains an unbalanced brace, for example s{foo}{bar} written across lines. If a section drifts sideways, that is usually why, and turning off statement splitting keeps the damage to indentation only. For a language where a full parser is available in the browser, try the Python Formatter or PHP Beautifier.

How to use

  1. Paste a .pl or .pm file into the left pane, or press Sample for a short script that tallies key value pairs.
  2. Set Indent to the width your project uses. Four spaces is the most common in Perl code.
  3. Leave Split statements onto new lines off unless the file arrived as one long line; it is riskier in Perl than in other languages.
  4. Save with Download, which writes formatted.pl.

Common questions

Is my regex safe from being reformatted?
The text of a regex is never edited. The only risk is a brace inside a regex being counted as a block, which shifts the indentation of the lines below it.
What happens to heredocs?
A Perl heredoc body is left on its own lines with its original whitespace, because changing it would change the string the program produces.
Does it touch POD documentation?
No. Everything from an equals directive in column one down to =cut is copied out verbatim.
Can it replace perltidy?
No. Perltidy runs the real Perl tokenizer and can rewrap expressions and align assignments. This page is a browser side re-indenter for a quick tidy up when installing a tool is not an option.