perl - How do I find a comment with PPI and then insert code before it? -


I am trying to find the comment # VERSION in a Perl source file. I want to insert the version before comment (or no place). Can anyone tell me the right way to do this?

First

  Use Strictly; Use warnings; Package My :: Package; # Version ...  

after

  harden; Use warnings; Package My :: Package; Our $ VERSION = 0.1; # VERSION ...  

Finally retaining the result # VERSION is optional

I actually have a how to find the # version There is some idea but a serialized PPI doctor has a regex that does not seem right, and is using the find_first on the second comment, but if it is not the first then I am not sure what to do

< P> Renewed code seems close to this correct solution because it only comments Sees. But I'm not sure how to use or actually how to create a new variable

  #! Use / usr / bin / env perl 5.012; Strict use; Use warnings; Use PPI; My $ PPI = PPI :: Document-> New ('test.pm'); My $ comments = $ ppi- & gt; Search ('ppi :: token :: comment'); My $ version = PPI :: Statement :: Variable-> New; Forex Currency (@ {$ Comments}) {If (/ ^ \ s * # \ s + VERSION \ b $ /) {$ _- & gt; Replace ($ version); }}  

UPDATE

Answer this question

Here are some code that you describe - it will start anyway that you start. It has been edited with (), which is a complete example of working with PPI (although its bits may not be the best practice):

  sub-make_model {### some stuff My $ modules = "lib / $ user_schema_path.pm"; My $ doctor = ppi :: document-> new ($ module); My $ digest_code = # some code is my $ comments = $ doc- & gt; Search (sub {$ _ [1] - & gt; ISA ('PPI :: token :: comment')}); My $ last_comment = $ comments- & gt; [$ # {$ Comments}]; $ Last_comment- & gt; Set_content ($ digest_code); $ Doctor & gt; ($ Modules); }  

I think that in your case you catch the $ Comments Serraf and change the first item that matches the replacement material / version /

And the last code here is courtesy of the poster:

  #! / Usr / bin / env perl Usage 5.012; Use warnings; Use PPI; My $ PPI = PPI :: Document-> New ('test.pm'); My $ comments = $ ppi- & gt; Search ('ppi :: token :: comment'); My $ version = 0.01; My $ _; Foreign Currency (@ {$ Comments}) {If (/ (^ (\ s *) (# \ s + version \ b) $ /) {my $ code = "$ 1" 'Our $ version =' "$ version $ 2 \ n "; $ _- & gt; set_content (" $ code ");}} $ Ppi- & gt; Save ('test1.pm');  

Comments

Popular posts from this blog

c# - sqlDecimal to decimal clr stored procedure Unable to cast object of type 'System.Data.SqlTypes.SqlDecimal' to type 'System.IConvertible' -

Calling GetGUIThreadInfo from Outlook VBA -

Obfuscating Python code? -