in reply to How can I find the calling object?

The method who_called() below will more or less do what you want. Caveats: Its not guaranteed to work. Read perlfunc::caller(). Note that there are some funky issues that mean you _cant_ reliable replace the overload::StrVal calls with plain old reference stringification.
package NewObj; sub new { return bless {},$_[0] }; package Foo; our @ISA=qw(NewObj); sub call_bar { my ($self,$bar)=@_; $bar->who_called; } package Bar; use strict; use warnings; use overload; #VITAL! our @ISA=qw(NewObj); sub who_called { my ($self)=@_; package DB; unless (my (undef,undef,undef,$sub)=caller(1)) { print "Called from main\n"; } else { print "Called from $sub\n"; if (ref($DB::args[0]) and overload::StrVal($DB::args[0])=~/=/) { print "\tWhich is a method that was invoked on ".overload::Str +Val($DB::args[0])."\n"; } else { print "@DB::args"; } } } package main; my $obj1=Foo->new(); my $obj2=Bar->new(); print "OBJ1 (Foo) : ".overload::StrVal($obj1)."\n" $obj1->call_bar($obj2);
HTH

--- demerphq
my friends call me, usually because I'm late....

Replies are listed 'Best First'.
Re: Re: How can I find the calling object?
by John M. Dlugosz (Monsignor) on Nov 19, 2002 at 19:21 UTC
    Note that there are some funky issues that mean you _cant_ reliable replace the overload::StrVal calls with plain old reference stringification.

    Do go on...

      To coin a phrase, a snippet is worth a thousand words...
      package Foo; use overload qw("" stringify fallback 1 + zero); sub stringify { "overload.pm just ruined your day!" } sub zero { 0 } package main; my $foo1=bless {},'Foo'; my $foo2=bless {},'Foo'; sub same { "'$_[0]' is ".($_[0] eq $_[1] ? "the same as" : "different +to" )." '$_[1]'\n" }; print same(0+$foo1,0+$foo2); print same($foo1,$foo2); print same("$foo1","$foo2"); print same(overload::StrVal($foo1),overload::StrVal($foo2)); __END__ '0' is the same as '0' 'overload.pm just ruined your day!' is the same as 'overload.pm just r +uined your day!' 'overload.pm just ruined your day!' is the same as 'overload.pm just r +uined your day!' 'Foo=HASH(0x1acef84)' is different to 'Foo=HASH(0x1acf038)'
      :-)

      AFAIK, the _only_ non-xs way to reliably determine the underlying variable type and class of an overloaded object is to parse the results of overload::StrVal. Even then you get nowhere with reblessed qr// objects. (Which still act as regexes at the same time.)

      Frankly the fact that perl completely lacks any reliable native perl way of doing type introspection is IMO one of its few serious failings. (And no, at least some of the problems do not go away with Scalar::Utils and List::Utils.)

      --- demerphq
      my friends call me, usually because I'm late....

        OK, you're saying that if the object overloads stringify, then you won't get the normal string for the hash or array.

        But what does parsing the StrVal left of the = sign do that ref() doesn't?