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

So I'm playing with Perl::Tk, and I'm a big fan of OOP, but I can't seem to merge the two because I need to pass function refs to make widgets. Is there a way to fake a function ref so that I can have an object encapsulating Tk?

Replies are listed 'Best First'.
Re: Fake a sub ref?
by Fletch (Bishop) on Feb 18, 2005 at 17:00 UTC

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

      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.

Re: Fake a sub ref?
by Mr. Muskrat (Canon) on Feb 18, 2005 at 17:19 UTC

    Based solely on your reply to Fletch, you haven't fully explained what you are trying to accomplish.

      No, I got it. Closures were the key.