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

Hi Monks,

Update: misunderstanding was somewhere else, this bit isn't the problem at all. Forget it!

I'm trying to understand what a bit of code is doing and I've got myself in a knot. In class A, there is a method that calls a class method of class B, with a code ref as an argument. Something like:

#in class A sub do_stuff{ my $self = shift; #1 Class::B->do_things(sub{ my $self = @_; #2 my $blah = Class::C->blah({ arg1=>$self->{blah}, #3 arg2=>self->{wibble} }) }) }
So, which class do the $selfs in the call to do_things actually refer to?
#1 - Class::A
#2 - Is this Class::B as the code is actually executed in the context of that class or is it Class::A - and if so, why?
#3 - does the $self->{blah} get interpolated in the context of Class::A before the code ref is even created, or is it still $self->{blah} in the code, in which case it will refer to whatever #2 means.

Thanks for any help!
Cass

</returns to banging head off desk>

Replies are listed 'Best First'.
Re: code ref confusion
by Joost (Canon) on Jun 30, 2004 at 11:57 UTC
    What class $self refers to is dependend on the caller, not the package it's in, this is especially true if you have subclasses:

    #!perl C::A->thing(); # prints "C::A"; C::B->thing(); # prints "C::B"; package C::A; sub thing { print shift; } package C::B; use base 'C::A';

    There is a bug in your code:

    my $self = @_; #2
    will set $self to the number of arguments to the anonymous sub, so this will not be what you want.

    #3 $self->{bla} - $self will be the $self created when the argument to Class::B->do_things is called. Where that is, I can't tell, because there is no definition of Class::B->do_things in this code.

    By the way, none of the variables are in package Class::B, because lexicals are not bound to classes anyway.

    Hope this helps
    Joost

      "There is a bug in your code:
      my $self = @_; #2 "

      Yeah, that was what part of what I didn't get - Actually args ( including $self) are passed to the anonymous sub when it is dereferenced. Once I realised that, it all made sense. Was just being a muppet. Thanks for your help though!

      Cxx