in reply to $object->UnrelatedPackage::some_subroutine()

More than that: it is quite common for me to use $widget->$methodname(@parameters); inside Tcl::Tk code.

Initially I used "eval" to find out method name but was very glad to discover this nifty feature, which makes implementation faster, strictier and safer.

In my case there were some non-trivial places with SUPER and inheritance due to heavy AUTOLOADING with further defining of newly created subroutine, but those were easy to implement
:)

Replies are listed 'Best First'.
Re^2: $object->UnrelatedPackage::some_subroutine()
by tilly (Archbishop) on Feb 19, 2005 at 02:25 UTC
    Random obscure trick for you:
    my $obj = bless {}; my $method_name = sub {"Just another Perl hacker,\n"}; print $obj->$method_name();
    I've used this when dealing with code that used the above trick to get a custom result without having to go and create a special method for it.

    Incidentally if you're using heavy AUTOLOADING, then you're probably better off assigning closures to typeglobs and getting rid of most of your AUTOLOADs. Not necessarily, but it tends to work well in my experience.

      I've used this when dealing with code that used the above trick to get a custom result without having to go and create a special method for it.

      This is fine for a quick and dirty solution, but I would be wary of using it for anything else.

      Perl's object system is somewhat broken as it is, so abusing it like this is just (IMO of course) a bad idea.

      -stvn
      Thanks for that knowledge bit.

      In my particular case this trick will not mess a program, because I use it inside AUTOLOAD so coderefs should not pass through.

      But...let's see, you can call

      $Tcl::Tk::Widget::AUTOLOAD=sub{print 'tricky hacky sub'}; Tcl::Tk::Widget::AUTOLOAD($object)
      Accidentally, it still not pass through as in that AUTOLOAD I see:
      my $method = $Tcl::Tk::Widget::AUTOLOAD; # Separate method to autoload from (sub)package $method =~ s/^(Tcl::Tk::Widget::((MainWindow|$ptk_w_names)::)?)// or die "weird inheritance ($method)";
      But I get your point: I should closer revise that module for similar things.

      Also, in my case, in Tcl::Tk module AUTOLOAD is used to redirect a method to Tcl/Tk system, so it is not OO trick but rather some kind of redirecting methods to Tcl/Tk.

      PS. I was talking about Tcl::Tk as I do not have anything other resembling OO

        When I suggested typeglobbing closures I didn't mean to create AUTOLOAD that way rather than using the usual subroutine definition, I meant that you should create lots of very similar subroutines from a central template rather than try to dynamically dispatch them from AUTOLOAD.

        There are a number of wins from doing so, two of the bigger ones being that it plays better with inheritance, and you don't have to put all of the dynamic logic in one big routine.