Sunday, 15 March 2015

perl - How does an object access the symbol table for the current package? -


How can I use the symbol table for the current package? For example, I have something like this:

  My $ object = MyModule-> new; # It appears in the current package, to see if Run_me is a function of the name, in I #, I would like to know that a sub-reference is $ object-> Do_your_job;   

If I use the __ package __ in the implementation of do_your_job , then in the MyModule package Will search How can I see it in the right package?

EDIT: I will try to clarify it. Let's say I have the following code:

  package MyMod; Sub new {return blessing}, $ _ [0]} sub do_your_job {my $ self = shift; # Of course find_package_of is fictitious here # Just for this example, $ pkg should be my $ pkg = find_package_of ($ self); If (defined & amp; amp; amp; {pkg. ':: run_me'}) {# function is present, it is called}} package main; The sub-run_me {print "X" should run me. \ N "; } My $ x = MyMod- & gt; new; # Run_me should meet in this current package and open it. $ X- & gt; Do_your_job;  

Now, $ x should be anyhow to note that the main is the current package, and its symbol table search I Scalar :: Util , but it still gave me MyModule instead of main . Hopefully, it's just a bit obvious now.

you just want

caller Tells the package from which it was called. (Here I added some standard pearl.)

  Use symbol qw & lt; Qualify_to_ref> # ... my $ pkg = caller; My $ symb = qualify_to_ref ('run_me', $ pkg); My $ run_me = * {$ symb} {CODE}; $ Run_me- & gt; () If set to $ run_me;  

To see it and see if it is defined and to call it, it will be duplicated because the standard Pearl does not do normal subxpress emissions, so that you 1) again This can be achieved, and 2) check the definition of the slot, and 3) Run it if it is defined.

Now if you make an object in a package and use it in another, then it is not going to be of great help. You need to add additional code such as 'owning_package' in the constructor.

Package MyMod; # ... sub new {# ... $ self- & gt; {Owning_package} = caller || 'Main'; # ...}

Now $ x-> In {owning_package} , there will be

main '.


No comments:

Post a Comment