This works, but is SOOOO wrong....

It uses the debugger, and some little-documented side-effects of "caller"

#!/usr/bin/perl -w package a; # the caller package sub new { return bless {},shift } sub call { my ($self,$other)=@_; $other->do_something; # calling the other. Notice: no $self } sub back { my $self=shift; print "I've been called back!\n"; print "And I have ",$self->{stuff},"\n"; } package b; # the called package use Data::Dumper; sub new { return bless {},shift } sub do_something { my $p=DB::get_args(); print Dumper($p); # this dumps the arguments of the caller (in this +case, a->call) $p->[0]->back() } package DB; # this MUST be called DB. It triggers magic in "caller" sub get_args { my @a=caller(2); # 2 because 0 is this, 1 is the one that called it, + 2 is the one we need. # no, you can't remove the assignment: the optimizer will kill the l +ine. return [@DB::args]; # @DB::args gets magically set to the param list +. } package main; $a=a->new;$b=b->new; $a->{stuff}='something'; $a->call(b); __END__

Will print:

$VAR1 = [ bless( { 'stuff' => 'something' }, 'a' ), 'b' ]; I've been called back! And I have something

UPDATE: clarified the meaning of the DB package


In reply to Re: How can I find the calling object? by dakkar
in thread How can I find the calling object? by strider corinth

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.