Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

How to redefine subroutines with Attribute::Handlers that run at BEGIN time?

by lestrrat (Deacon)
on Oct 03, 2003 at 19:37 UTC ( [id://296371]=perlquestion: print w/replies, xml ) Need Help??

lestrrat has asked for the wisdom of the Perl Monks concerning the following question:

I basically want to put a wrapper around a function when it's declared with a particular attribute. This would normally be easy, because when the handler is run, you get a reference to the symbol, so you can do this:

sub myhandler : ATTR(CODE) { my($pkg, $symbol, $referent....) = @_; ... *{$symbol} = sub { # additional code goto &$referent; } }

However, the script(s) that uses the attribute is called from do(). That means that the CHECK and INIT blocks are not run. I tried changing the handler to be invoked at BEGIN time, but the problem there is that the $symbol is a string that says "ANON". So I have no where I can assign the newly generate sub.

Does anybody know a way to workaround this?

Replies are listed 'Best First'.
Re: How to redefine subroutines with Attribute::Handlers that run at BEGIN time?
by tilly (Archbishop) on Oct 05, 2003 at 17:52 UTC
    I would suggest reporting your difficulty to p5p and hope that your feedback will help improve the implementation of attributes to make your problem go away.

    In the meantime my preferred solution would be to refactor your code so that the code which needs to be wrapped is not called from do. If that won't work, then the best that I can think of is to provide a function which does the wraps, and make sure that the scripts which need it call that at the top of the script, at runtime.

Re: How to redefine subroutines with Attribute::Handlers that run at BEGIN time?
by Juerd (Abbot) on Oct 15, 2003 at 06:52 UTC

    So I have no where I can assign the newly generate sub.

    Maybe with Data::Swap, you can work around this problem. I haven't tried yet, but I'm thinking of something like

    use Data::Swap; sub myhandler : ATTR(CODE) { my ($p, $s, $r, ...) = @_; swap $r, \my $o; swap $r, sub { # code &$o; }; }
    I have no idea if this would work.

    Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://296371]
Approved by ybiC
Front-paged by broquaint
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-03-28 10:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found