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

Greetings. When a few scripts share some constants, I like to make a file like this
#constants.pl package Const; $important_number = 2
and then use it like this:
#somescript.pl require 'constants.pl'; print "Think about this: ", $Const::important_number, "\n";
But alas, faithful applying the "-w" option to all my doings, I am punished with a warning: "Name "Const::important_number" used only once: possible typo at somescript.pl line 3." Any wisdom on how to avoid this?

Replies are listed 'Best First'.
RE: Namespace woes
by t0mas (Priest) on Jun 13, 2000 at 13:06 UTC
    Placing
    use warnings qw(all); no warnings qw(once);
    somewhere will fix that.

    /brother t0mas
        Sorry, forgot to mention that. Got a bit carried away by the new functionality.

        /brother t0mas
Re: Namespace woes
by btrott (Parson) on Jun 13, 2000 at 20:40 UTC
    You could investigate using Exporter to export the variables into your namespace.

    Or you could put the require in a BEGIN block:

    BEGIN { require 'const.pl' }
    which loads the library at compile-time, so the variables are declared.
Re: Namespace woes
by chromatic (Archbishop) on Jun 13, 2000 at 21:17 UTC
    btrott's BEGIN solution is quite good. You also might consider making your constants.pl file a module. Simply rename it to 'constants.pm', make sure it's in the same directory as your other files, and check to see that the absolute last statement returns true (ie, if you put functions in there, add the line '1;' at the very end).

    Then, change the require line to use constants;. See perlmod for more gory details.

    Update: Yes, that should be PM not PL. Thanks for pointing it out, plaid and gregorovius!

      chromatic probably means 'constants.pm'. Rename it to 'constants.pm' so the 'use' statement recognizes it without having to append the file extension.
RE: Namespace woes
by Adam (Vicar) on Jun 13, 2000 at 21:06 UTC
    I ran into a similar problem once. I inherited a script which generated this warning for much the same reason that yours does. I found the offending variable in a line like this:
    NO_WARNING( $variable );
    And I found an evil line elsewhere that said:
    sub NO_WARNING{}
    Well, when I went searching for the source of this problem I found out that this had been implemented to avoid the typo warning, but then someone noticed that the constant wasn't being used and deleted it. This left only the sad attempt to silence the warning. Bad, very bad.

    My recommendation is to declare constants as subroutines. This not only avoids the warnings but makes the variable immutable.

    sub Constant(){2}
    Makes Constant alway return 2. Also, you can place these in a .pm perl module and import them that way so that you don't clutter your namespace.