3 Perl::Tidy - Parses and beautifies perl source
9 my $error_flag = Perl::Tidy::perltidy(
11 destination => $destination,
14 perltidyrc => $perltidyrc,
16 errorfile => $errorfile,
18 debugfile => $debugfile,
19 formatter => $formatter, # callback object (see below)
20 dump_options => $dump_options,
21 dump_options_type => $dump_options_type,
22 prefilter => $prefilter_coderef,
23 postfilter => $postfilter_coderef,
28 This module makes the functionality of the perltidy utility available to perl
29 scripts. Any or all of the input parameters may be omitted, in which case the
30 @ARGV array will be used to provide input parameters as described
31 in the perltidy(1) man page.
33 For example, the perltidy script is basically just this:
36 Perl::Tidy::perltidy();
38 The call to B<perltidy> returns a scalar B<$error_flag> which is TRUE if an
39 error caused premature termination, and FALSE if the process ran to normal
40 completion. Additional discuss of errors is contained below in the L<ERROR
43 The module accepts input and output streams by a variety of methods.
44 The following list of parameters may be any of the following: a
45 filename, an ARRAY reference, a SCALAR reference, or an object with
46 either a B<getline> or B<print> method, as appropriate.
48 source - the source of the script to be formatted
49 destination - the destination of the formatted output
50 stderr - standard error output
51 perltidyrc - the .perltidyrc file
52 logfile - the .LOG file stream, if any
53 errorfile - the .ERR file stream, if any
54 dump_options - ref to a hash to receive parameters (see below),
55 dump_options_type - controls contents of dump_options
56 dump_getopt_flags - ref to a hash to receive Getopt flags
57 dump_options_category - ref to a hash giving category of options
58 dump_abbreviations - ref to a hash giving all abbreviations
60 The following chart illustrates the logic used to decide how to
63 ref($param) $param is assumed to be:
64 ----------- ---------------------
68 (other) object with getline (if source) or print method
70 If the parameter is an object, and the object has a B<close> method, that
71 close method will be called at the end of the stream.
77 If the B<source> parameter is given, it defines the source of the input stream.
78 If an input stream is defined with the B<source> parameter then no other source
79 filenames may be specified in the @ARGV array or B<argv> parameter.
83 If the B<destination> parameter is given, it will be used to define the
84 file or memory location to receive output of perltidy.
88 The B<stderr> parameter allows the calling program to redirect the stream that
89 would otherwise go to the standard error output device to any of the stream
90 types listed above. This stream contains important warnings and errors
91 related to the parameters passed to perltidy.
95 If the B<perltidyrc> file is given, it will be used instead of any
96 F<.perltidyrc> configuration file that would otherwise be used.
100 The B<errorfile> parameter allows the calling program to capture
101 the stream that would otherwise go to either a .ERR file. This
102 stream contains warnings or errors related to the contents of one
103 source file or stream.
105 The reason that this is different from the stderr stream is that when perltidy
106 is called to process multiple files there will be up to one .ERR file created
107 for each file and it would be very confusing if they were combined.
109 However if perltidy is called to process just a single perl script then it may
110 be more convenient to combine the B<errorfile> stream with the B<stderr>
111 stream. This can be done by setting the B<-se> parameter, in which case this
112 parameter is ignored.
116 The B<logfile> parameter allows the calling program to capture the log stream.
117 This stream is only created if requested with a B<-g> parameter. It contains
118 detailed diagnostic information about a script which may be useful for
123 The B<teefile> parameter allows the calling program to capture the tee stream.
124 This stream is only created if requested with one of the 'tee' parameters,
125 a B<--tee-pod> , B<--tee-block-comments>, B<--tee-side-commnts>, or B<--tee-all-comments>.
129 The B<debugfile> parameter allows the calling program to capture the stream
130 produced by the B<--DEBUG> parameter. This parameter is mainly used for
131 debugging perltidy itself.
135 If the B<argv> parameter is given, it will be used instead of the
136 B<@ARGV> array. The B<argv> parameter may be a string, a reference to a
137 string, or a reference to an array. If it is a string or reference to a
138 string, it will be parsed into an array of items just as if it were a
143 If the B<dump_options> parameter is given, it must be the reference to a hash.
144 In this case, the parameters contained in any perltidyrc configuration file
145 will be placed in this hash and perltidy will return immediately. This is
146 equivalent to running perltidy with --dump-options, except that the parameters
147 are returned in a hash rather than dumped to standard output. Also, by default
148 only the parameters in the perltidyrc file are returned, but this can be
149 changed (see the next parameter). This parameter provides a convenient method
150 for external programs to read a perltidyrc file. An example program using
151 this feature, F<perltidyrc_dump.pl>, is included in the distribution.
153 Any combination of the B<dump_> parameters may be used together.
155 =item dump_options_type
157 This parameter is a string which can be used to control the parameters placed
158 in the hash reference supplied by B<dump_options>. The possible values are
159 'perltidyrc' (default) and 'full'. The 'full' parameter causes both the
160 default options plus any options found in a perltidyrc file to be returned.
162 =item dump_getopt_flags
164 If the B<dump_getopt_flags> parameter is given, it must be the reference to a
165 hash. This hash will receive all of the parameters that perltidy understands
166 and flags that are passed to Getopt::Long. This parameter may be
167 used alone or with the B<dump_options> flag. Perltidy will
168 exit immediately after filling this hash. See the demo program
169 F<perltidyrc_dump.pl> for example usage.
171 =item dump_options_category
173 If the B<dump_options_category> parameter is given, it must be the reference to a
174 hash. This hash will receive a hash with keys equal to all long parameter names
175 and values equal to the title of the corresponding section of the perltidy manual.
176 See the demo program F<perltidyrc_dump.pl> for example usage.
178 =item dump_abbreviations
180 If the B<dump_abbreviations> parameter is given, it must be the reference to a
181 hash. This hash will receive all abbreviations used by Perl::Tidy. See the
182 demo program F<perltidyrc_dump.pl> for example usage.
186 A code reference that will be applied to the source before tidying. It is
187 expected to take the full content as a string in its input, and output the
192 A code reference that will be applied to the tidied result before outputting.
193 It is expected to take the full content as a string in its input, and output
194 the transformed content.
196 Note: A convenient way to check the function of your custom prefilter and
197 postfilter code is to use the --notidy option, first with just the prefilter
198 and then with both the prefilter and postfilter. See also the file
199 B<filter_example.pl> in the perltidy distribution.
203 =head1 ERROR HANDLING
205 An exit value of 0, 1, or 2 is returned by perltidy to indicate the status of the result.
207 A exit value of 0 indicates that perltidy ran to completion with no error messages.
209 An exit value of 1 indicates that the process had to be terminated early due to
210 errors in the input parameters. This can happen for example if a parameter is
211 misspelled or given an invalid value. The calling program should check for
212 this flag because if it is set the destination stream will be empty or
213 incomplete and should be ignored. Error messages in the B<stderr> stream will
214 indicate the cause of any problem.
216 An exit value of 2 indicates that perltidy ran to completion but there there
217 are warning messages in the B<stderr> stream related to parameter errors or
218 conflicts and/or warning messages in the B<errorfile> stream relating to
219 possible syntax errors in the source code being tidied.
221 In the event of a catastrophic error for which recovery is not possible
222 B<perltidy> terminates by making calls to B<croak> or B<confess> to help the
223 programmer localize the problem. These should normally only occur during
226 =head1 NOTES ON FORMATTING PARAMETERS
228 Parameters which control formatting may be passed in several ways: in a
229 F<.perltidyrc> configuration file, in the B<perltidyrc> parameter, and in the
232 The B<-syn> (B<--check-syntax>) flag may be used with all source and
233 destination streams except for standard input and output. However
234 data streams which are not associated with a filename will
235 be copied to a temporary file before being passed to Perl. This
236 use of temporary files can cause somewhat confusing output from Perl.
238 If the B<-pbp> style is used it will typically be necessary to also
239 specify a B<-nst> flag. This is necessary to turn off the B<-st> flag
240 contained in the B<-pbp> parameter set which otherwise would direct
241 the output stream to the standard output.
245 The following example uses string references to hold the input and output
246 code and error streams, and illustrates checking for errors.
250 my $source_string = <<'EOT';
251 my$error=Perl::Tidy::perltidy(argv=>$argv,source=>\$source_string,
252 destination=>\$dest_string,stderr=>\$stderr_string,
253 errorfile=>\$errorfile_string,);
258 my $errorfile_string;
259 my $argv = "-npro"; # Ignore any .perltidyrc at this site
260 $argv .= " -pbp"; # Format according to perl best practices
261 $argv .= " -nst"; # Must turn off -st in case -pbp is specified
262 $argv .= " -se"; # -se appends the errorfile to stderr
263 ## $argv .= " --spell-check"; # uncomment to trigger an error
265 print "<<RAW SOURCE>>\n$source_string\n";
267 my $error = Perl::Tidy::perltidy(
269 source => \$source_string,
270 destination => \$dest_string,
271 stderr => \$stderr_string,
272 errorfile => \$errorfile_string, # ignored when -se flag is set
273 ##phasers => 'stun', # uncomment to trigger an error
278 # serious error in input parameters, no tidied output
279 print "<<STDERR>>\n$stderr_string\n";
280 die "Exiting because of serious errors\n";
283 if ($dest_string) { print "<<TIDIED SOURCE>>\n$dest_string\n" }
284 if ($stderr_string) { print "<<STDERR>>\n$stderr_string\n" }
285 if ($errorfile_string) { print "<<.ERR file>>\n$errorfile_string\n" }
287 Additional examples are given in examples section of the perltidy distribution.
289 =head1 Using the B<formatter> Callback Object
291 The B<formatter> parameter is an optional callback object which allows
292 the calling program to receive tokenized lines directly from perltidy for
293 further specialized processing. When this parameter is used, the two
294 formatting options which are built into perltidy (beautification or
295 html) are ignored. The following diagram illustrates the logical flow:
297 |-- (normal route) -> code beautification
298 caller->perltidy->|-- (-html flag ) -> create html
299 |-- (formatter given)-> callback to write_line
301 This can be useful for processing perl scripts in some way. The
302 parameter C<$formatter> in the perltidy call,
304 formatter => $formatter,
306 is an object created by the caller with a C<write_line> method which
307 will accept and process tokenized lines, one line per call. Here is
308 a simple example of a C<write_line> which merely prints the line number,
309 the line type (as determined by perltidy), and the text of the line:
313 # This is called from perltidy line-by-line
315 my $line_of_tokens = shift;
316 my $line_type = $line_of_tokens->{_line_type};
317 my $input_line_number = $line_of_tokens->{_line_number};
318 my $input_line = $line_of_tokens->{_line_text};
319 print "$input_line_number:$line_type:$input_line";
322 The complete program, B<perllinetype>, is contained in the examples section of
323 the source distribution. As this example shows, the callback method
324 receives a parameter B<$line_of_tokens>, which is a reference to a hash
325 of other useful information. This example uses these hash entries:
327 $line_of_tokens->{_line_number} - the line number (1,2,...)
328 $line_of_tokens->{_line_text} - the text of the line
329 $line_of_tokens->{_line_type} - the type of the line, one of:
331 SYSTEM - system-specific code before hash-bang line
332 CODE - line of perl code (including comments)
333 POD_START - line starting pod, such as '=head'
334 POD - pod documentation text
335 POD_END - last line of pod section, '=cut'
336 HERE - text of here-document
337 HERE_END - last line of here-doc (target word)
338 FORMAT - format section
339 FORMAT_END - last line of format section, '.'
340 DATA_START - __DATA__ line
341 DATA - unidentified text following __DATA__
342 END_START - __END__ line
343 END - unidentified text following __END__
344 ERROR - we are in big trouble, probably not a perl script
346 Most applications will be only interested in lines of type B<CODE>. For
347 another example, let's write a program which checks for one of the
348 so-called I<naughty matching variables> C<&`>, C<$&>, and C<$'>, which
349 can slow down processing. Here is a B<write_line>, from the example
350 program B<find_naughty.pl>, which does that:
354 # This is called back from perltidy line-by-line
355 # We're looking for $`, $&, and $'
356 my ( $self, $line_of_tokens ) = @_;
358 # pull out some stuff we might need
359 my $line_type = $line_of_tokens->{_line_type};
360 my $input_line_number = $line_of_tokens->{_line_number};
361 my $input_line = $line_of_tokens->{_line_text};
362 my $rtoken_type = $line_of_tokens->{_rtoken_type};
363 my $rtokens = $line_of_tokens->{_rtokens};
366 # skip comments, pod, etc
367 return if ( $line_type ne 'CODE' );
369 # loop over tokens looking for $`, $&, and $'
370 for ( my $j = 0 ; $j < @$rtoken_type ; $j++ ) {
372 # we only want to examine token types 'i' (identifier)
373 next unless $$rtoken_type[$j] eq 'i';
375 # pull out the actual token text
376 my $token = $$rtokens[$j];
379 if ( $token =~ /^\$[\`\&\']$/ ) {
381 "$input_line_number: $token\n";
386 This example pulls out these tokenization variables from the $line_of_tokens
389 $rtoken_type = $line_of_tokens->{_rtoken_type};
390 $rtokens = $line_of_tokens->{_rtokens};
392 The variable C<$rtoken_type> is a reference to an array of token type codes,
393 and C<$rtokens> is a reference to a corresponding array of token text.
394 These are obviously only defined for lines of type B<CODE>.
395 Perltidy classifies tokens into types, and has a brief code for each type.
396 You can get a complete list at any time by running perltidy from the
399 perltidy --dump-token-types
401 In the present example, we are only looking for tokens of type B<i>
402 (identifiers), so the for loop skips past all other types. When an
403 identifier is found, its actual text is checked to see if it is one
404 being sought. If so, the above write_line prints the token and its
407 The B<formatter> feature is relatively new in perltidy, and further
408 documentation needs to be written to complete its description. However,
409 several example programs have been written and can be found in the
410 B<examples> section of the source distribution. Probably the best way
411 to get started is to find one of the examples which most closely matches
412 your application and start modifying it.
414 For help with perltidy's peculiar way of breaking lines into tokens, you
415 might run, from the command line,
419 where F<filename> is a short script of interest. This will produce
420 F<filename.DEBUG> with interleaved lines of text and their token types.
421 The B<-D> flag has been in perltidy from the beginning for this purpose.
422 If you want to see the code which creates this file, it is
423 C<write_debug_entry> in Tidy.pm.
431 The module 'Perl::Tidy' comes with a binary 'perltidy' which is installed when the module is installed. The module name is case-sensitive. For example, the basic command for installing with cpanm is 'cpanm Perl::Tidy'.
435 This man page documents Perl::Tidy version 20210717
439 This package is free software; you can redistribute it and/or modify it
440 under the terms of the "GNU General Public License".
442 Please refer to the file "COPYING" for details.
446 A list of current bugs and issues can be found at the CPAN site L<https://rt.cpan.org/Public/Dist/Display.html?Name=Perl-Tidy>
448 To report a new bug or problem, use the link on this page.
450 The source code repository is at L<https://github.com/perltidy/perltidy>.
454 The perltidy(1) man page describes all of the features of perltidy. It
455 can be found at http://perltidy.sourceforge.net.