3 Perl::Tidy - Parses and beautifies perl source
9 my $error_flag = Perl::Tidy::perltidy(
11 destination => $destination,
14 perltidyrc => $perltidyrc,
16 errorfile => $errorfile,
17 formatter => $formatter, # callback object (see below)
18 dump_options => $dump_options,
19 dump_options_type => $dump_options_type,
20 prefilter => $prefilter_coderef,
21 postfilter => $postfilter_coderef,
26 This module makes the functionality of the perltidy utility available to perl
27 scripts. Any or all of the input parameters may be omitted, in which case the
28 @ARGV array will be used to provide input parameters as described
29 in the perltidy(1) man page.
31 For example, the perltidy script is basically just this:
34 Perl::Tidy::perltidy();
36 The call to B<perltidy> returns a scalar B<$error_flag> which is TRUE if an
37 error caused premature termination, and FALSE if the process ran to normal
38 completion. Additional discuss of errors is contained below in the L<ERROR
41 The module accepts input and output streams by a variety of methods.
42 The following list of parameters may be any of the following: a
43 filename, an ARRAY reference, a SCALAR reference, or an object with
44 either a B<getline> or B<print> method, as appropriate.
46 source - the source of the script to be formatted
47 destination - the destination of the formatted output
48 stderr - standard error output
49 perltidyrc - the .perltidyrc file
50 logfile - the .LOG file stream, if any
51 errorfile - the .ERR file stream, if any
52 dump_options - ref to a hash to receive parameters (see below),
53 dump_options_type - controls contents of dump_options
54 dump_getopt_flags - ref to a hash to receive Getopt flags
55 dump_options_category - ref to a hash giving category of options
56 dump_abbreviations - ref to a hash giving all abbreviations
58 The following chart illustrates the logic used to decide how to
61 ref($param) $param is assumed to be:
62 ----------- ---------------------
66 (other) object with getline (if source) or print method
68 If the parameter is an object, and the object has a B<close> method, that
69 close method will be called at the end of the stream.
75 If the B<source> parameter is given, it defines the source of the input stream.
76 If an input stream is defined with the B<source> parameter then no other source
77 filenames may be specified in the @ARGV array or B<argv> parameter.
81 If the B<destination> parameter is given, it will be used to define the
82 file or memory location to receive output of perltidy.
86 The B<stderr> parameter allows the calling program to redirect the stream that
87 would otherwise go to the standard error output device to any of the stream
88 types listed above. This stream contains important warnings and errors
89 related to the parameters passed to perltidy.
93 If the B<perltidyrc> file is given, it will be used instead of any
94 F<.perltidyrc> configuration file that would otherwise be used.
98 The B<errorfile> parameter allows the calling program to capture
99 the stream that would otherwise go to either a .ERR file. This
100 stream contains warnings or errors related to the contents of one
101 source file or stream.
103 The reason that this is different from the stderr stream is that when perltidy
104 is called to process multiple files there will be up to one .ERR file created
105 for each file and it would be very confusing if they were combined.
107 However if perltidy is called to process just a single perl script then it may
108 be more convenient to combine the B<errorfile> stream with the B<stderr>
109 stream. This can be done by setting the B<-se> parameter, in which case this
110 parameter is ignored.
114 The B<logfile> parameter allows the calling program to capture
115 the stream that would otherwise go to a .LOG file. This
116 stream is only created if requested with a B<-g> parameter. It
117 contains detailed diagnostic information about a script
118 which may be useful for debugging.
122 If the B<argv> parameter is given, it will be used instead of the
123 B<@ARGV> array. The B<argv> parameter may be a string, a reference to a
124 string, or a reference to an array. If it is a string or reference to a
125 string, it will be parsed into an array of items just as if it were a
130 If the B<dump_options> parameter is given, it must be the reference to a hash.
131 In this case, the parameters contained in any perltidyrc configuration file
132 will be placed in this hash and perltidy will return immediately. This is
133 equivalent to running perltidy with --dump-options, except that the perameters
134 are returned in a hash rather than dumped to standard output. Also, by default
135 only the parameters in the perltidyrc file are returned, but this can be
136 changed (see the next parameter). This parameter provides a convenient method
137 for external programs to read a perltidyrc file. An example program using
138 this feature, F<perltidyrc_dump.pl>, is included in the distribution.
140 Any combination of the B<dump_> parameters may be used together.
142 =item dump_options_type
144 This parameter is a string which can be used to control the parameters placed
145 in the hash reference supplied by B<dump_options>. The possible values are
146 'perltidyrc' (default) and 'full'. The 'full' parameter causes both the
147 default options plus any options found in a perltidyrc file to be returned.
149 =item dump_getopt_flags
151 If the B<dump_getopt_flags> parameter is given, it must be the reference to a
152 hash. This hash will receive all of the parameters that perltidy understands
153 and flags that are passed to Getopt::Long. This parameter may be
154 used alone or with the B<dump_options> flag. Perltidy will
155 exit immediately after filling this hash. See the demo program
156 F<perltidyrc_dump.pl> for example usage.
158 =item dump_options_category
160 If the B<dump_options_category> parameter is given, it must be the reference to a
161 hash. This hash will receive a hash with keys equal to all long parameter names
162 and values equal to the title of the corresponding section of the perltidy manual.
163 See the demo program F<perltidyrc_dump.pl> for example usage.
165 =item dump_abbreviations
167 If the B<dump_abbreviations> parameter is given, it must be the reference to a
168 hash. This hash will receive all abbreviations used by Perl::Tidy. See the
169 demo program F<perltidyrc_dump.pl> for example usage.
173 A code reference that will be applied to the source before tidying. It is
174 expected to take the full content as a string in its input, and output the
179 A code reference that will be applied to the tidied result before outputting.
180 It is expected to take the full content as a string in its input, and output
181 the transformed content.
183 Note: A convenient way to check the function of your custom prefilter and
184 postfilter code is to use the --notidy option, first with just the prefilter
185 and then with both the prefilter and postfilter. See also the file
186 B<filter_example.pl> in the perltidy distribution.
190 =head1 ERROR HANDLING
192 Perltidy will return with an error flag indicating if the process had to be
193 terminated early due to errors in the input parameters. This can happen for
194 example if a parameter is misspelled or given an invalid value. The calling
195 program should check this flag because if it is set the destination stream will
196 be empty or incomplete and should be ignored. Error messages in the B<stderr>
197 stream will indicate the cause of any problem.
199 If the error flag is not set then perltidy ran to completion. However there
200 may still be warning messages in the B<stderr> stream related to control
201 parameters, and there may be warning messages in the B<errorfile> stream
202 relating to possible syntax errors in the source code being tidied.
204 In the event of a catastrophic error for which recovery is not possible
205 B<perltidy> terminates by making calls to B<croak> or B<confess> to help the
206 programmer localize the problem. These should normally only occur during
209 =head1 NOTES ON FORMATTING PARAMETERS
211 Parameters which control formatting may be passed in several ways: in a
212 F<.perltidyrc> configuration file, in the B<perltidyrc> parameter, and in the
215 The B<-syn> (B<--check-syntax>) flag may be used with all source and
216 destination streams except for standard input and output. However
217 data streams which are not associated with a filename will
218 be copied to a temporary file before being be passed to Perl. This
219 use of temporary files can cause somewhat confusing output from Perl.
221 If the B<-pbp> style is used it will typically be necessary to also
222 specify a B<-nst> flag. This is necessary to turn off the B<-st> flag
223 contained in the B<-pbp> parameter set which otherwise would direct
224 the output stream to the standard output.
228 The following example uses string references to hold the input and output
229 code and error streams, and illustrates checking for errors.
233 my $source_string = <<'EOT';
234 my$error=Perl::Tidy::perltidy(argv=>$argv,source=>\$source_string,
235 destination=>\$dest_string,stderr=>\$stderr_string,
236 errorfile=>\$errorfile_string,);
241 my $errorfile_string;
242 my $argv = "-npro"; # Ignore any .perltidyrc at this site
243 $argv .= " -pbp"; # Format according to perl best practices
244 $argv .= " -nst"; # Must turn off -st in case -pbp is specified
245 $argv .= " -se"; # -se appends the errorfile to stderr
246 ## $argv .= " --spell-check"; # uncomment to trigger an error
248 print "<<RAW SOURCE>>\n$source_string\n";
250 my $error = Perl::Tidy::perltidy(
252 source => \$source_string,
253 destination => \$dest_string,
254 stderr => \$stderr_string,
255 errorfile => \$errorfile_string, # ignored when -se flag is set
256 ##phasers => 'stun', # uncomment to trigger an error
261 # serious error in input parameters, no tidied output
262 print "<<STDERR>>\n$stderr_string\n";
263 die "Exiting because of serious errors\n";
266 if ($dest_string) { print "<<TIDIED SOURCE>>\n$dest_string\n" }
267 if ($stderr_string) { print "<<STDERR>>\n$stderr_string\n" }
268 if ($errorfile_string) { print "<<.ERR file>>\n$errorfile_string\n" }
270 Additional examples are given in examples section of the perltidy distribution.
272 =head1 Using the B<formatter> Callback Object
274 The B<formatter> parameter is an optional callback object which allows
275 the calling program to receive tokenized lines directly from perltidy for
276 further specialized processing. When this parameter is used, the two
277 formatting options which are built into perltidy (beautification or
278 html) are ignored. The following diagram illustrates the logical flow:
280 |-- (normal route) -> code beautification
281 caller->perltidy->|-- (-html flag ) -> create html
282 |-- (formatter given)-> callback to write_line
284 This can be useful for processing perl scripts in some way. The
285 parameter C<$formatter> in the perltidy call,
287 formatter => $formatter,
289 is an object created by the caller with a C<write_line> method which
290 will accept and process tokenized lines, one line per call. Here is
291 a simple example of a C<write_line> which merely prints the line number,
292 the line type (as determined by perltidy), and the text of the line:
296 # This is called from perltidy line-by-line
298 my $line_of_tokens = shift;
299 my $line_type = $line_of_tokens->{_line_type};
300 my $input_line_number = $line_of_tokens->{_line_number};
301 my $input_line = $line_of_tokens->{_line_text};
302 print "$input_line_number:$line_type:$input_line";
305 The complete program, B<perllinetype>, is contained in the examples section of
306 the source distribution. As this example shows, the callback method
307 receives a parameter B<$line_of_tokens>, which is a reference to a hash
308 of other useful information. This example uses these hash entries:
310 $line_of_tokens->{_line_number} - the line number (1,2,...)
311 $line_of_tokens->{_line_text} - the text of the line
312 $line_of_tokens->{_line_type} - the type of the line, one of:
314 SYSTEM - system-specific code before hash-bang line
315 CODE - line of perl code (including comments)
316 POD_START - line starting pod, such as '=head'
317 POD - pod documentation text
318 POD_END - last line of pod section, '=cut'
319 HERE - text of here-document
320 HERE_END - last line of here-doc (target word)
321 FORMAT - format section
322 FORMAT_END - last line of format section, '.'
323 DATA_START - __DATA__ line
324 DATA - unidentified text following __DATA__
325 END_START - __END__ line
326 END - unidentified text following __END__
327 ERROR - we are in big trouble, probably not a perl script
329 Most applications will be only interested in lines of type B<CODE>. For
330 another example, let's write a program which checks for one of the
331 so-called I<naughty matching variables> C<&`>, C<$&>, and C<$'>, which
332 can slow down processing. Here is a B<write_line>, from the example
333 program B<find_naughty.pl>, which does that:
337 # This is called back from perltidy line-by-line
338 # We're looking for $`, $&, and $'
339 my ( $self, $line_of_tokens ) = @_;
341 # pull out some stuff we might need
342 my $line_type = $line_of_tokens->{_line_type};
343 my $input_line_number = $line_of_tokens->{_line_number};
344 my $input_line = $line_of_tokens->{_line_text};
345 my $rtoken_type = $line_of_tokens->{_rtoken_type};
346 my $rtokens = $line_of_tokens->{_rtokens};
349 # skip comments, pod, etc
350 return if ( $line_type ne 'CODE' );
352 # loop over tokens looking for $`, $&, and $'
353 for ( my $j = 0 ; $j < @$rtoken_type ; $j++ ) {
355 # we only want to examine token types 'i' (identifier)
356 next unless $$rtoken_type[$j] eq 'i';
358 # pull out the actual token text
359 my $token = $$rtokens[$j];
362 if ( $token =~ /^\$[\`\&\']$/ ) {
364 "$input_line_number: $token\n";
369 This example pulls out these tokenization variables from the $line_of_tokens
372 $rtoken_type = $line_of_tokens->{_rtoken_type};
373 $rtokens = $line_of_tokens->{_rtokens};
375 The variable C<$rtoken_type> is a reference to an array of token type codes,
376 and C<$rtokens> is a reference to a corresponding array of token text.
377 These are obviously only defined for lines of type B<CODE>.
378 Perltidy classifies tokens into types, and has a brief code for each type.
379 You can get a complete list at any time by running perltidy from the
382 perltidy --dump-token-types
384 In the present example, we are only looking for tokens of type B<i>
385 (identifiers), so the for loop skips past all other types. When an
386 identifier is found, its actual text is checked to see if it is one
387 being sought. If so, the above write_line prints the token and its
390 The B<formatter> feature is relatively new in perltidy, and further
391 documentation needs to be written to complete its description. However,
392 several example programs have been written and can be found in the
393 B<examples> section of the source distribution. Probably the best way
394 to get started is to find one of the examples which most closely matches
395 your application and start modifying it.
397 For help with perltidy's peculiar way of breaking lines into tokens, you
398 might run, from the command line,
402 where F<filename> is a short script of interest. This will produce
403 F<filename.DEBUG> with interleaved lines of text and their token types.
404 The B<-D> flag has been in perltidy from the beginning for this purpose.
405 If you want to see the code which creates this file, it is
406 C<write_debug_entry> in Tidy.pm.
414 Thanks to Hugh Myers who developed the initial modular interface
419 This man page documents Perl::Tidy version 20130922.
423 This package is free software; you can redistribute it and/or modify it
424 under the terms of the "GNU General Public License".
426 Please refer to the file "COPYING" for details.
431 perltidy at users.sourceforge.net
435 The perltidy(1) man page describes all of the features of perltidy. It
436 can be found at http://perltidy.sourceforge.net.