Interception of nonexistent calling methods in Perl

I am trying to intercept non-existent calling methods in some subclass. Yes, I know about AUTOLOAD, but (for methods) it first tries to call parent :: method, then UNIVERSAL :: method, and only then :: AUTOLOAD. But I first need to call (something like) :: AUTOLOAD. Since I want to know which subclasses of methods they are trying to call from the parent.

Give me some advice about this, please.

+7
source share
3 answers
  • If you just want to know what methods are used, you can use some profiling module, for example Devel :: NYTProf.

  • If you want to respond to this while your program is running, you can directly capture the entersub operation code in the same way as profiling modules. See perlguts code or profiling module code for more information.

  • Perhaps you could create a โ€œMonitorโ€ class with FETCH and EXISTS and bind it to a character hash table, for example: tie% Module :: Name ::, Monitor;

But if we donโ€™t know exactly what you are trying to do and why, itโ€™s hard to guess what will be the right solution for you.

+1
source

Take a close look at Jiri Cloudaโ€™s suggestion that you step back and review what you are trying to accomplish. You almost never want to do what you are trying to do.

But, if you're really sure you want it, here's how to get enough pure Perl rope to hang yourself ...

subs pragma takes a list of subheadings for pre-launch. As Tchrist said above, you can predict the subtitles, but not really define them. This will be a short circuit method to send to superclasses and immediately call your AUTOLOAD.

As for the list of subscriptions to go to pragma, you can use Class :: Inspector-> methods (thanks to Nick Gibson's answer to find out about this module).

According to Brian d foy, Nic Nic Gibson's answer, Class :: Inspector will not process methods defined in UNIVERSAL. If you need to do this separately, you can get inspiration from the "use subs" line in my Class :: LazyObject module.

+1
source

Why not create a sub AUTOLOAD in a subclass package that 1) reports the missing method, and then 2) sends the call to the parent. For this, you did not define @ISA in the subclass.

Something like:

 package my_parent; sub foo { warn "in my_parent::foo" } package my_subclass; my $PARENT_CLASS = "my_parent"; # assume only one parent # Note: no @ISA defined here sub AUTOLOAD { warn "non-existent method $AUTOLOAD called\n"; my $self = shift; (my $method = $AUTOLOAD) =~ s{.*::}{}; my $super = $PARENT_CLASS . '::' . $method; $self->$super(@_); } package main; my $x = bless {}, 'my_subclass'; $x->foo; 

Syntax: $self->$super(@_) , where $super has double colons, it tells perl where the package starts looking for a method, for example:

 $self->my_parent::foo(...) 

will look for the foo method starting in the my_parent package, without which the $self class will not be implemented.

0
source

All Articles