On Wed, Mar 10, 2004 at 02:16:50PM -0600, Michael C. Davis wrote:
> Hi, I saw this neat trick while looking at AppConfig.pm on CPAN. It lets
> you define configuration variables in a file and, having read them, access
> them either by name-as-string OR as a function having the name of the
> variable, like so (copied from the CPAN documentation):
>
> # create/define combined
> my $config = AppConfig->new(\%cfg,
> $varname => \%varopts, $varname => \%varopts, ...);
>
> # set/get the value
> $config->set($varname, $value);
> $config->get($varname);
>
> # shortcut form
> $config->varname($value);
> $config->varname();
>
> It's that last part labeled "shortcut form" that I'm interested in.
>
> I've read through the module's code once and didn't catch the part where
> they auto-define the var-named functions for you. What should I be looking
> for, and/or how would one implement this?
>
> Obviously I could just write subroutines having the same names as
> configuration variables, but it's the "automagically appears" aspect that
> looks especially useful.
The magic is in the AUTOLOAD sub. perldoc perlsub for more details.
The following code is hacked out from one of my modules and pared down:
sub AUTOLOAD
{
my $func = $AUTOLOAD;
$func =~ s/^.*:://;
no strict "refs";
*$func = sub
{
...
};
goto &$func
}
--
Paul Johnson - [EMAIL PROTECTED]
http://www.pjcj.net
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>