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

If I have two classes. And class B inherits from class A and I call a method from class B that is only in class A - how do I get at the name of the calling class - rather than the class where the method was found.

Using Log4Perl and class inheritance is causing my logfiles to be less than readable.
Simon
  • Comment on How to identify calling class whilst in inherited method

Replies are listed 'Best First'.
Re: How to identify calling class whilst in inherited method
by broquaint (Abbot) on Dec 19, 2003 at 11:00 UTC
    Just look at what called the method e.g
    sub A::func { print "called by: ", ref $_[0] || $_[0] } @B::ISA = 'A'; my $o = bless [] => 'B'; $o->func; __output__ called by: B
    HTH

    _________
    broquaint

Re: How to identify calling class whilst in inherited method
by Corion (Patriarch) on Dec 19, 2003 at 11:08 UTC

    The class of your current object would be ref $self and the class where the method is defined in would be __PACKAGE__ (or CLASS, if you use CLASS.pm). I'm not sure if this is the answer you're looking for, but maybe Carp gives you more hints about walking the caller chain to find what information you want. rubyisms.pm also does some funky caller walking to make self behave like $_[0]...

    perl -MHTTP::Daemon -MHTTP::Response -MLWP::Simple -e ' ; # The $d = new HTTP::Daemon and fork and getprint $d->url and exit;#spider ($c = $d->accept())->get_request(); $c->send_response( new #in the HTTP::Response(200,$_,$_,qq(Just another Perl hacker\n))); ' # web
Re: How to identify calling class whilst in inherited method
by Marcello (Hermit) on Dec 19, 2003 at 12:46 UTC
    More interestingly,

    I have a similar problem, but I want to know which class AND which method called the method in a baseclass. Does anybody know how to use caller() to get this data? I remember running into problems when using an eval() in the calling method.

    Thanks.

    Marcel

    Update: Think I've found it:
    sub GetCaller { my $self = shift; my $i = 0; my $result; while (1) { my ($package, $filename, $line, $subroutine) = caller($i++); if (defined($package) && ($package ne "main")) { $result = $subroutine; } else { last; } }; return $result; }
    I ignore "main" because this is always a startup script.