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

Hi, I'm trying to make some stuff in my module configurable via AppConfig but can't get it to work. What I'd like to do is give it a configfile like this:
use Blah ( Config => '/home/me/config.txt' );
My code: module Blah:
package Blah; use AppConfig; my $config = AppConfig->new(); sub import { my (%args) = @_; if ( $args{'Config'} ) { $config->file($args{'Config'}); } #### next few lines for testing only use Data::Dumper; print Dumper(\%args); } use Othermodule ( Config => $config );
If I add 'use Blah (Config => "/configfile")' to my code it doesn't seem to pass the config to 'Othermodule'. Where am I going wrong?

Replies are listed 'Best First'.
Re: use Module (LIST) and 'import'
by duff (Parson) on Nov 30, 2004 at 21:08 UTC

    You don't understand the order in which things are executed I think. The use OtherModule part happens before $config is modified by import. Remember that use Blah qw(foo) is shorthand for BEGIN { require Blah; import Blah qw(foo); }. The use Othermodule happens when you require Blah which is before import has had a chance to run.

      OK that's clear, thanks! Is there some other way to achieve my goal of being able to specify a config-parameter in a 'use'-statement and be able to pass it to other modules?
        This can be done like so:
        package Blah; use AppConfig; my $config = AppConfig->new(); sub import { my (%args) = @_; if ( $args{'Config'} ) { $config->file($args{'Config'}); } require OtherModule; OtherModule->import(Config => $config); #### next few lines for testing only use Data::Dumper; print Dumper(\%args); }
        --Stevie-O
        $"=$,,$_=q>|\p4<6 8p<M/_|<('=> .q>.<4-KI<l|2$<6%s!<qn#F<>;$, .=pack'N*',"@{[unpack'C*',$_] }"for split/</;$_=$,,y[A-Z a-z] {}cd;print lc
Re: use Module (LIST) and 'import'
by ysth (Canon) on Dec 01, 2004 at 05:45 UTC
    In addition to the execution order problem, you also need to adjust for the fact that import is called as a method call (e.g. Blah->import(Config=>'/home/me/config.txt') in your case), so the first thing in @_ is the name of the used module. You should have: my ($pkg, %args) = @_;
Re: use Module (LIST) and 'import'
by rrwo (Friar) on Dec 02, 2004 at 01:00 UTC

    The use line is called during compilation, so $config is not yet set. Try the following:

    BEGIN { $config = AppConfig->new(); } use Othermodule ( Config => $config );