Perrin Harkins wrote:
> On Tue, Oct 7, 2008 at 5:03 PM, Matt Hucke <[EMAIL PROTECTED]> wrote:
>> Is there any way to prevent TT from calling functions that don't exist and 
>> falling into AUTOLOAD?
> 
> I think you want to implement can() in your module.

I use can() within Autoload.   I'm doing something like this (simplified here:)

package MyDerivedClass;
our @ISA = qw(MyBaseClass);
...

package MyBaseClass;

sub AUTOLOAD
{
     unless ($AUTOLOAD =~ m/(.*)::([^:]+)/)             ## classname::function
     {
         die("I don't understand function name $AUTOLOAD.");
     }

     my $classname = $1;
     my $func = $2;

     if (my $fp = MyBaseClass->can($func))
     {
        return &$fp(@_, classname => $classname);       
        # most functions of MyBaseClass know what to do with a classname => X 
parameter
     } else {
        die("$classname doesn't know how to $func");
     }  

}

When I call
        [% foo.hashkey %]
either for a hashkey that is known to exist or one that's not yet defined (but 
might, under some 
circumstances, be defined - I don't want undef to be an error), it dies at the 
second 'die()' above.
I've put in a temporary kluge (not shown) where it checks if $_[0] is the right 
class to be $self, 
and returns $self->{$func} (interpreting the so-called function name as a hash 
key), but this has 
the side effect that any undefined function name called by accident (in the 
main program as well as 
from a template) is now a function that returns '' - and that's very bad.

<p relevance="tangential">
The reason for this AUTOLOAD is that I want to inherit functions that are 
called without an existing 
object ( called "static" in other languages), for which @ISA is ignored; most 
of these are 
object-creation functions.  I've been doing things like
        $objects = MyDerivedClass::factoryLoad(database => $db, query => 
whatever);
(This line appears in packages that are not subclasses of the base class in 
question - for which I 
don't want to muddy up their namespace with Exporter).

Without the AUTOLOAD, I had to make a factoryLoad function within 
MyDerivedClass - it's just a 
wrapper that calls the base class's loader with "classname => __PACKAGE__" 
stuck on the end.  I hate 
these little stub functions, and thought AUTOLOAD could mimic them for me - 
this worked beautifully 
until I tried to use one of these in a template, and found it calling AUTOLOAD 
for every attempt to 
access a variable.
</p>

thanks, matt.

-- 
[EMAIL PROTECTED]
http://www.graveyards.com

_______________________________________________
templates mailing list
templates@template-toolkit.org
http://mail.template-toolkit.org/mailman/listinfo/templates

Reply via email to