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

dear perlmonks,

i want to create a constant file and use it without the package name in other file. this is what i did,

///// MyConst.pm //////////// package MyConst; use Readonly; Readonly::Scalar $const1 => 1; ///////// END ////////////
////// test.pl ///////// use MyConst; print $const1; ////////// END //////////
i got this error: "Global symbol "$const1" requires explicit package name at MyConst.pm line 4

it doesn't matter if i call "$const1" or "$MyConst::const1", same error as above, maybe i just don't understand Perl namespace, any help will be greatly appreciated.

Thanks!

Replies are listed 'Best First'.
Re: how to create a constant file and use it in other file
by pc88mxer (Vicar) on Jul 16, 2008 at 00:13 UTC
    Referring to $MyConst::const1 works for me:
    use strict; use warnings; use MyConst; print $MyConst::const1, "\n"; # prints 1
      sorry i just forget that i put "use strict;" in "MyConst.pm" file, without that line, it works; with that line, i got the compile error.
        Then just add:
        our $const1;
        to MyConst.pm (just before the Readonly declaration.)

        Update: To use a variable in another package without requiring a prefix, you would have to import the symbol from the other package. The standard way to do this is to have MyConst be a subclass of Exporter.

        oh, i am using perl v5.6.1

        can you use the constant data without prefixing it with the package name? ( $const1 instead of $MyConst::const1 )