When I use "$module->prune( 'PPI::Token::Whitespace' );" and save the results in $file is there an ease way back to working code for the saved code? I tried "Perl::Tidy" and it looks much better after this but id does not fix all.
#!/usr/bin/env perl
use warnings;
use 5.012;
use PPI;
my $file = 'my_file.pm';
my $module = PPI::Document->new( $file );
$module->prune( 'PPI::Token::Pod' );
$module->prune( 'PPI::Token::Comment' );
$module->prune( 'PPI::Token::Whitespace' );
# ...
# ...
$module->save( $file ) or die $!;
edit:
I am no longer able to reconstruct my code that I had in the first place. With prune-whitespace enabled I could use something like this
$a = $module->find( sub {
$_[1]->isa('PPI::Statement') and
$_[1]->content eq q(if($@){$have_Term_ReadKey=0;$have_Term_Size=1;eval'require "Term/Size.pm"';if($@){$have_Term_Size=0;}})
});
instead of
$a = $module->find( sub {
$_[1]->isa('PPI::Statement') and
$_[1]->schild(0)->content eq q(if) and
$_[1]->schild(1)->isa('PPI::Something') and
...
...
});
to find a point to append something. But know after retrying I think it can not work (apart from the fact, that I can not restore the code without withespaces).
Some whitespace is significant and in general you will break your code if you remove it:
use PPI;
$document = PPI::Document->new(\'sub sq{$_[0]**2}');
$document->prune('PPI::Token::Whitespace');
print $document->serialize;
The output of this program is:
subsq{$_[0]**2}
Oops. There's nothing Perl::Tidy
can do about that.
It would be safe (I think -- can't think of a counterexample) to remove the top-level whitespace
# just prune top-level whitespace
$document->prune( sub { $_[1]->parent->isa('PPI::Document')
and $_[1]->isa('PPI::Token::Whitespace') } );
Enumerating all the other rules (like "whitespace between two PPI::Token::Word
elements is not safe to remove") sounds like a hard problem, though.