]> git.donarmstrong.com Git - perltidy.git/blob - examples/perllinetype.pl
[svn-inject] Installing original source of perltidy
[perltidy.git] / examples / perllinetype.pl
1 #!/usr/bin/perl -w
2 use strict;
3
4 # For each line in a perl script, write to STDOUT lines of the form
5 # line number : line type : line text
6 #
7 # usage:
8 # perllinetype myfile.pl >myfile.new
9 # perllinetype <myfile.pl >myfile.new
10 #
11 # This file is one of the examples distributed with perltidy and is a
12 # simple demonstration of using a callback object with Perl::Tidy.
13 #
14 # Steve Hancock, July 2003
15 #
16 use Getopt::Std;
17 use Perl::Tidy;
18 use IO::File;
19 $| = 1;
20 use vars qw($opt_h);
21 my $usage = <<EOM;
22    usage: perllinetype filename >outfile
23 EOM
24 getopts('h') or die "$usage";
25 if ($opt_h) { die $usage }
26
27 # Make the source for perltidy, which will be a filehandle
28 # or just '-' if the source is stdin
29 my ($file, $fh, $source);
30 if ( @ARGV == 0 ) {
31     $source = '-';
32 }
33 elsif ( @ARGV == 1 ) {
34     $file = $ARGV[0];
35     $fh = IO::File->new( $file, 'r' );
36     unless ($fh) { die "cannot open '$file': $!\n" }
37     $source = $fh;
38 }
39 else { die $usage }
40
41 # make the callback object
42 my $formatter = MyFormatter->new(); 
43
44 my $dest;
45
46 # start perltidy, which will start calling our write_line()
47 perltidy(
48     'formatter'   => $formatter,     # callback object
49     'source'      => $source,
50     'destination' => \$dest,         # (not really needed)
51     'argv'        => "-npro -se",    # dont need .perltidyrc
52                                      # errors to STDOUT
53 );
54 $fh->close() if $fh;
55
56 package MyFormatter;
57
58 sub new {
59     my ($class) = @_;
60     bless {}, $class;
61 }
62
63 sub write_line {
64
65     # This is called from perltidy line-by-line
66     my $self              = shift;
67     my $line_of_tokens    = shift;
68     my $line_type         = $line_of_tokens->{_line_type};
69     my $input_line_number = $line_of_tokens->{_line_number};
70     my $input_line        = $line_of_tokens->{_line_text};
71     print "$input_line_number:$line_type:$input_line";
72 }
73
74 # called once after the last line of a file
75 sub finish_formatting {
76     my $self = shift;
77     return;
78 }