Perl FAQ 3.4: Is there a pretty-printer (similar to indent(1)) for Perl?

Perl FAQ 3.4

Is there a pretty-printer (similar to indent(1)) for Perl?

That depends on what you mean. If you want something that works like vgrind on Perl programs, then the answer is ``yes, nearly''. Here's a vgrind entry for perl:


PERL|perl|Perl:\
    :pb=^\d?(sub|package)\d\p\d:\
    :bb={:be=}:cb=#:ce=$:sb=":se=\e":lb=':\
    :le=\e':tl:\
    :id=_:\
    :kw=\
    if for foreach unless until while continue else elsif \
    do eval require \
    die exit \
    defined delete reset \
    goto last redo next dump \
    local undef return  \
    write format  \
    sub package

It doesn't actually do everything right; in particular, things like $#, $', s#/foo##, and $foo'bar all confuse it.

David Levine uses this:

# perl 4.x                    David Levine <levine@ics.uci.edu> 05 apr 1993
# Derived from Tom Christiansen's perl vgrindef.  I'd like to treat all  of
# perl's built-ins as  keywords,  but vgrind   fields are  limited  to 1024
# characters  and the built-ins overflow that (surprise  :-).  So, I didn't
# include the dbm*, end*, get*, msg*, sem*, set*,  and  shm* functions.   I
# couldn't come up with an easy way to  distinguish beginnings  of literals
# ('...') from package prefixes, so literals are not marked.
# Be sure to:
# 1) include whitespace between a subprogram name and its opening {
# 2) include whitespace before a comment (so that $# doesn't get
# interpreted as one).
perl4:\
	:pb=^\d?(sub|package)\d\p\d:\
	:id=$%@_:\
	:bb=\e{:be=\e}:cb=\d\e#:ce=$:sb=\e":se=\e":\
	:kw=accept alarm atan2 bind binmode caller chdir chmod chop \
chown chroot close closedir connect continue cos crypt defined delete \
die do dump each else elsif eof eval exec exit exp fcntl fileno flock \
for foreach fork format getc gmtime goto grep hex if include index int \
ioctl join keys kill last length link listen local localtime log lstat \
m mkdir next oct open opendir ord pack package pipe pop print printf \
push q qq qx rand read readdir readlink recv redo rename require reset \
return reverse rewinddir rindex rmdir s scalar seek seekdir select send \
shift shutdown sin sleep socket socketpair sort splice split sprintf \
sqrt srand stat study sub substr symlink syscall sysread system \
syswrite tell telldir time times tr truncate umask undef unless unlink \
unpack unshift until utime values vec wait waitpid wantarray warn while \
write y: 

If what you mean is whether there is a program that will reformat the program much as indent(1) will do for C, then the answer is no. The complex feedback between the scanner and the parser (as in the things that confuse vgrind) make it challenging at best to write a stand-alone Perl parser.

Of course, if you follow the guidelines in perlstyle(1), you shouldn't need to reformat.


Other resources at this site: