Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Over riding autoloaded sub

by falinf (Novice)
on Jun 30, 2010 at 13:33 UTC ( [id://847328]=perlquestion: print w/replies, xml ) Need Help??

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

greetings, I want to override a sub in CGI.pm that is auotloaded. I still need to call the original sub, so I have to stash a reference to it.

Is there any way to do this w/o having to uselessly call the sub one time, so that it's instantiated? I haven't been able to find anyway to do it without calling it at least once, then I can stash its address my $orig = \&CGI::subname and proceed to override it.

thanks for any insight!

Replies are listed 'Best First'.
Re: Over riding autoloaded sub
by Corion (Patriarch) on Jun 30, 2010 at 13:53 UTC

    If CGI implements ->can, you should be able to get to a code reference that does what you want:

    my $old_method; BEGIN { $old_method = CGI->can('header'); }; sub CGI::header { print "Before\n"; $old_method->(@_); print "After\n"; };

    Otherwise, I wouldn't mess around with CGI and its namespace but implement a thin class that just delegates to CGI:

    package MyFakeCGI; use CGI; sub new { my ($class,%options) = @_; $options{ cgi } ||= CGI->new; my $self = \%options; bless $self => $class; }; sub header { my $self = shift; print "Before\n"; $_[0]->{cgi}->header->(@_); print "After\n"; }; # Delegate everything else to CGI sub AUTOLOAD { goto &CGI::AUTOLOAD; }; # Don't delegate DESTROY sub DESTROY {}; 1;
Re: Over riding autoloaded sub
by Taulmarill (Deacon) on Jun 30, 2010 at 13:44 UTC

    You don't have to stash a reference to a sub in order to call it. I don't really know what you are trying to do. Please provide a minimal example showing what you tried similar to the following code and tell us what doesn't work

    use strict; use warnings; use CGI qw/:standard/; sub header { return "this is not the header you are looking for\n"; } print header; print CGI::header; print main::header;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2024-04-25 11:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found