in reply to Fake a sub ref?

Just make a coderef that calls the correct method: sub { $someobj->whatever( @_ ) }

Replies are listed 'Best First'.
Re^2: Fake a sub ref?
by Anonymous Monk on Feb 18, 2005 at 17:06 UTC
    That still requires a global instance of the object, which I want to avoid. Note the requirement of a pre-existing $someobj.

      Um, no, it doesn't. It's called a closure. It's a wonderful aspect of perl. It latches on to the $someobj that is visible at the time that the code ref is created, even if it's a my $someobj in the surrounding function. Yes, $someobj has to pre-exist, but it doesn't need to be global.

      Not true. It only requires a global instance of the object OR a pre-existing $someobj, not both.

      Pre-existing:

      sub create_closure { my ($obj) = @_; return sub { print($obj, $/); }; } my $sub; { my $existing_obj = 1234; my $sub = create_closure($existing_obj); } &$sub(); # Prints 1234, even though $existing_obj is out of scope.

      Global:

      our $global_obj; $global_obj = 1234; my $sub = sub { print($global_obj, $/); }; $global_obj = 5678; &$sub(); # Prints 5678.
      Why?

      Sorry if I am being obtuse here, I have spent the last three months on an OOP based Tk project and I dont seem to be having the same problem. A logical portion of the Tk interface is packaged in an object oriented module. COntrol over the Tk is done by the metods. Anything that an outsider needs to do is also run by a method. If two object onstances need to communicate (I have to do this a lot) then you set-up a method to handle it!

      Perhaps you could be a little more explicit about your problem.

      jdtoronto

      No, that requires a lexical $someobj which contains at the time of the creation of the anonymous coderef a reference to the instance you want to call the method upon. See perldoc -q closure.

        That's a great idea... I think a closure would work perfectly here.