in reply to Re: Fake a sub ref?
in thread Fake a sub ref?

That still requires a global instance of the object, which I want to avoid. Note the requirement of a pre-existing $someobj.

Replies are listed 'Best First'.
Re^3: Fake a sub ref?
by ikegami (Patriarch) on Feb 18, 2005 at 17:49 UTC

    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.
Re^3: Fake a sub ref?
by Tanktalus (Canon) on Feb 18, 2005 at 17:28 UTC

    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.

Re^3: Fake a sub ref?
by jdtoronto (Prior) on Feb 18, 2005 at 17:22 UTC
    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

Re^3: Fake a sub ref?
by Fletch (Bishop) on Feb 18, 2005 at 17:29 UTC

    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.