I want to have a file where I define a set of constants and then be able to require that file from others and have those constants available. For some reason though I can't seem to get this to work. I have something like this setup...
constants.pl
use constant
{
MY_CONSTANT1 => 1,
MY_CONSTANT2 => 2,
MY_CONSTANT3 => 3,
MY_CONSTANT4 => 4
};
sub useConstants
{
#able to use constants fine in here...
my $var = MY_CONSTANT4;
print "$var\n"; #outputs '4'
}
1;
main.pl
#!/usr/bin/perl
#use strict; # If I uncomment this line it won't compile because it c
+laims MY_CONSTANT3 is a bareword and not a constant.
require "constants.pl";
#if I call useConstants this sub can use them just fine.
useConstants();
#However if I try to use a constant that should've been defined in con
+stants.pl here it won't work!
my $var = MY_CONSTANT3;
print "$var\n"; #outputs 'MY_CONSTANT3' !! Why won't it output '3'?
exit 1;
output...
me@mybox:/test
>perl main.pl
4
MY_CONSTANT3
me@mybox:/test
>
If I add a use strict; in to the top of main.pl this won't even compile because it says MY_CONSTANT3 is a bareword and isn't allowed. I don't understand. Isn't constants.pl in the main namespace too? Why wouldn't it still be visible? What can I do to accomplish having a set of constants that can be shared across multiple files?
Thanks,