Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Extract subroutines from a Perl script. OR: "Only perl can parse Perl." But can it help me to do so?

by theorbtwo (Prior)
on Sep 24, 2004 at 12:17 UTC ( #393472=note: print w/ replies, xml ) Need Help??


in reply to Extract subroutines from a Perl script. OR: "Only perl can parse Perl." But can it help me to do so?

Well, the first question to ask is, "can I run the code in order to find out more about it". This isn't just a question of security, mind you -- some scripts take action at BEGIN time that you'd prefer to avoid.

If you can't, you run afowl of the meaning of the "Only perl can parse Perl" quote -- as something other then the perl interpreter (even if it's written in Perl) trying to parse Perl (the language), you aren't going to be able to do a perfect job. You can do a /decent/ job, using complex regexes, PPI, or even simple regexes and Text::Balanced.

If you /can/, then a whole world of introspection opens up to you. perl has already parsed the program (or will parse the program, depending on when you're talking about, which depends on how you structure your program.) You can walk the symbol tables to find your subs, and use some B magic to find the begin and end lines.

To whit: Given a coderef, running B::svref_2object on it will give you an object somewhere in the B tree (I don't quite recall; B::SVRV quite likely; let's call it $cv). Running $cv->GV->LINE, according to my comments, gives you the line number of the /last/ line of the sub. $cv->FILE; will give you the filename. $cv->START; will give you the opcode where execution starts. If this ISA B::COP (and it always will be), then you can call ->line on it, to get it's line number. IIRC, that's the line number of the first /statement/ within the sub, not of the sub foo { line.


Warning: Unless otherwise stated, code is untested. Do not use without understanding. Code is posted in the hopes it is useful, but without warranty. All copyrights are relinquished into the public domain unless otherwise stated. I am not an angel. I am capable of error, and err on a fairly regular basis. If I made a mistake, please let me know (such as by replying to this node).


Comment on Re: Extract subroutines from a Perl script. OR: "Only perl can parse Perl." But can it help me to do so?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://393472]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (8)
As of 2014-08-22 10:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (153 votes), past polls