How to find a comment on PPI and then paste the code in front of it?

I am trying to find the # VERSION comment in the perl source file. Then I want to insert the version before the comment (or it doesn't matter instead). Can someone tell me the correct way to do this using PPI ?

before

 use strict; use warnings; package My::Package; # VERSION ... 

after

 use strict; use warnings; package My::Package; our $VERSION = 0.1;# VERSION ... 

saving # VERSION in the final result is optional

I actually have a couple of ideas on how to find # VERSION, but one of them is a regular expression of a serialized ppi document that doesn't seem to be correct, and the other uses find_first for comments, but if it's not the first, I'm not sure what to do.

Updated code . This seems like the right solution as it only considers comments. but I'm not sure how to use or really how to create a new variable.

 #!/usr/bin/env perl use 5.012; use strict; use warnings; use PPI; my $ppi = PPI::Document->new('test.pm'); my $comments = $ppi->find('PPI::Token::Comment'); my $version = PPI::Statement::Variable->new; foreach ( @{$comments} ) { if ( /^\s*#\s+VERSION\b$/ ) { $_->replace($version); } } 

UPDATE

The answer to this question became the basis for DZP :: OurPkgVersion

+4
source share
1 answer

Here is some code that does something like what you described - you will start anyway. He edited Catalyst :: Helper :: AuthDBIC ( source ), which is a complete example of working with PPI (although its bits may not be the best):

 sub make_model { ### snip some stuff my $module = "lib/$user_schema_path.pm"; my $doc = PPI::Document->new($module); my $digest_code = # some code my $comments = $doc->find( sub { $_[1]->isa('PPI::Token::Comment')} ); my $last_comment = $comments->[$#{$comments}]; $last_comment->set_content($digest_code); $doc->save($module); } 

I suppose in your case you grab the $ comments arrayref and change the first element that matches / VERSION / with replaceable content.

And here is the final code, kindly provided by the poster:

 #!/usr/bin/env perl use 5.012; use warnings; use PPI; my $ppi = PPI::Document->new('test.pm'); my $comments = $ppi->find('PPI::Token::Comment'); my $version = 0.01; my $_; foreach ( @{$comments} ) { if ( /^(\s*)(#\s+VERSION\b)$/ ) { my $code = "$1" . 'our $VERSION = ' . "$version;$2\n"; $_->set_content("$code"); } } $ppi->save('test1.pm'); 
+4
source

All Articles