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

I am trying to make a configuration file which another perl script reads. Looking at other peoples scripts they all use require() and wrap it in a BEGIN block which works fine but not in this case since I am using $dir in the filename and $dir is dependent on %ENV which isn't known at compile time I guess. What I get is a "Undefined subroutine" error. Something I don't understand, why would it even matter if it's in a BEGIN block? The require()'s come before the usage of those constants anyway so it shouldn't matter?

Example:

#config.pl use strict; eval 'use constant SOMETHING => "asdf"' unless(defined(\&SOMETHING)); 1; #test.pl use strict; use File::Basename; my $dir = dirname($ENV{"SCRIPT_FILENAME"})."/"; require("${dir}config.pl"); print &SOMETHING;
  • Comment on Constants imported from other perl scripts doesn't want to exist :(
  • Download Code

Replies are listed 'Best First'.
Re: Constants imported from other perl scripts doesn't want to exist :(
by Errto (Vicar) on Sep 17, 2005 at 18:52 UTC
    The problem is actually in your unless clause. According to the docs for defined, the way to tell if a subroutine is defined is to simply call defined(&SOMETHING). Putting the backslash in front of it will actually cause it to return a valid (non-undef) reference value, albeit to an undefined subroutine.
Re: Constants imported from other perl scripts doesn't want to exist :(
by borisz (Canon) on Sep 17, 2005 at 18:54 UTC
    The problem is you test unless(defined (\&SOMETHING));
    but you want unless ( defined(&SOMETHING));.
    Boris
      I changed it but it didn't make any difference.
        I'm sure, you have a typo somewhere. This should work.
        use strict; eval 'use constant SOMETHING => "asdf"' unless(defined(&SOMETHING)); 1;
        Boris
Re: Constants imported from other perl scripts doesn't want to exist :(
by shady (Sexton) on Sep 17, 2005 at 19:04 UTC
    I suggest you make configuration module config.pm and to declare standart interface for it. Then you may to define all config parameters inside this module and export it. For example:
    package config; use strict; use Exporter; our (@ISA, @EXPORT, @EXPORT_OK); @ISA = qw(Exporter); @EXPORT = qw($param_1, $param_2, $param_3); our $param_1 = 'foo'; our $param_2 = 'bar'; ... 1;
Re: Constants imported from other perl scripts doesn't want to exist :(
by phaylon (Curate) on Sep 17, 2005 at 18:51 UTC
    Well,
    BEGIN { if ( $ENV{TEST} ) { use constant FOOBAR => 23, } } print 'Foobar: ', FOOBAR, "\n";
    works just fine, if it's that what you're looking for.

    Ordinary morality is for ordinary people. -- Aleister Crowley