[Chicago-talk] calling functions in a package by its name

Matt Hucke hucke at cynico.net
Thu Jan 17 09:47:01 PST 2008

>> sub getConfig   # public API, implemented by lots of similar classes
>> {
>>      return \%secretStuff;
>> }
> First off %secretStuff isn't secret, it's a package variable.  

Right; what I was trying to show was that the dynamically-loaded module might store configuration 
info in any arbitrary unknown place it wants, but would be required to always have a function 
(getConfig() or somesuch) that would return it.

>>      my $prog = "use $classname;";
>>      eval $prog; die("eval '$prog' failed with " . $@ ) if ($@);
> You do have to use string eval to load the class.  require is better
> than use here, though.  (Do you want $class->import to be called?  Not
> for classes, usually.)

OK, I'll give eval "require.." a try.  It definitely should not import things into the caller's 
namespace - this thing is basically just an object factory.

> Yes, of course we can :)  And now you don't need eval.  This applies to
> methods also:
>   my $foo = $class->$constructor(@args);

Beautiful!  And 'use strict' doesn't even complain.  I was trying all sorts of convolutions of 
&{...} and $func=\&something and the like; didn't think that the solution would be so simple and 

> No, it's harmful because of:
>   my $class = "Foo; `rm -rf *`"

True.  I left it out of the demo program, but where I'm doing it for real I pass all the class names 
through a regex that cleans them up.

> How about:
>   my $class = 'Foo';
>   eval "require $class";
>   $class->can('new')->(); # Foo->new()

I'll give that a try.

> print returns 1 when it works, so main will usually return 1.  This
> means you exit with failure status no matter what.  Potentially a bug.

Sorry - the demo script was cobbled together in ten minutes, and I got sloppy.

>> The project is a web framework that allows for object types to be specified in the config file: 
> Writing your own web framework, eh.  I tried that once.
> http://catalyst.perl.org/

I looked into Catalyst a few years back - it's quite impressive.  But it was sufficiently different 
from the way I'd been doing things already - and from the mountain of legacy code on my employer's 
server - that I chose to instead do something I could ease into slowly.  My "Baldrick" project thus 
evolved out of the way I'd been doing things already.

Thanks for the advice - I'll be removing a few stringy evals from the production code today.

hucke at cynico.net

More information about the Chicago-talk mailing list