4 # Example script for removing trailing blank lines of code from a perl script
5 # This is from the examples/ directory of the perltidy distribution and may
6 # be modified as needed.
8 # This was written in response to RT #118553, "leave only one newline at end of file".
9 # Adding the requested feature to perltidy itself would have very undesirable
10 # side-effects when perltidy is operated from within an editor. So it is best
11 # done with a separate filter script on entire files.
14 # delete_ending_blank_lines.pl myfile.pl >myfile.new
15 # delete_ending_blank_lines.pl <myfile.pl >myfile.new
22 usage: $0 filename >outfile
24 getopts('h') or die "$usage";
25 if ($opt_h) { die $usage }
27 # Make the source for perltidy, which will be a filehandle
28 # or just '-' if the source is stdin
29 my ($file, $fh, $source);
33 elsif ( @ARGV == 1 ) {
35 $fh = IO::File->new( $file, 'r' );
36 unless ($fh) { die "cannot open '$file': $!\n" }
41 # make the callback object
42 my $formatter = MyFormatter->new();
46 # start perltidy, which will start calling our write_line()
48 'formatter' => $formatter, # callback object
50 'destination' => \$dest, # (not really needed)
51 'argv' => "-npro -se", # dont need .perltidyrc
55 die "Error calling perltidy\n";
70 # This is called from perltidy line-by-line; we just save lines
72 my $line_of_tokens = shift;
73 push @lines, $line_of_tokens;
76 # called once after the last line of a file
77 sub finish_formatting {
80 # remove all trailing blank lines of code
81 while (my $line_of_tokens = pop(@lines)) {
82 my $line_type = $line_of_tokens->{_line_type};
83 my $input_line = $line_of_tokens->{_line_text};
84 if ( $line_type eq 'CODE' ) {
86 next unless ($input_line);
88 push @lines, $line_of_tokens;
92 # write remaining lines
93 foreach my $line_of_tokens (@lines) {
94 my $line_type = $line_of_tokens->{_line_type};
95 my $input_line = $line_of_tokens->{_line_text};