develooper Front page | perl.beginners | Postings from February 2009

2 files, 1 package, shared constants

Thread Next
Stanisław T. Findeisen
February 25, 2009 02:44
2 files, 1 package, shared constants
Message ID:
Hash: SHA1

Hello there

My application consists of several files. Some of them are to be run as
CGI scripts, the others from command line. There is also a "common" file
with constants and shared routines.

The question is: what is the most standard way to export constants from
that common file so that they could be used in the other files?

Here is a minimal example:

- -------- --------
package MyPackage;

use warnings;
use strict;

use constant {
~    MY_FIRST_CONSTANT => 'hello world!'

*MY_SECOND_CONSTANT = [1, 3, 7];

sub routine1 {
~    print "Hello from routine1! $MyPackage::MY_SECOND_CONSTANT\n";

# This is to satisfy require()

- -------- --------
package MyPackage;

use warnings;
use strict;

require '';

print 'The 1st constant is: ' . MyPackage->MY_FIRST_CONSTANT . "\n";
print 'The 2nd constant is: ' . *MY_SECOND_CONSTANT . "\n";
print '             SCALAR: ' . ${*MY_SECOND_CONSTANT{SCALAR}} . "\n";
print '              ARRAY: ' . join(', ',


- ----------------

This produces output like this:

$ perl ./
The 1st constant is: hello world!
The 2nd constant is: *MyPackage::MY_SECOND_CONSTANT
~             SCALAR: 729
~              ARRAY: 1, 3, 7
Hello from routine1! 729

Funny thing is that in MyPackage->MY_FIRST_CONSTANT works, but
neither of these:

print '' . MY_FIRST_CONSTANT . "\n";
print '' . MyPackage::MY_FIRST_CONSTANT . "\n";

Bareword "MY_FIRST_CONSTANT" not allowed while "strict subs" in use at
./ line ***.
Execution of ./ aborted due to compilation errors.

So I suspect that although I managed to solve the problem, the solution
with MyPackage->MY_FIRST_CONSTANT is a bug in Perl or something?? Why
should I be able to call the constant subroutine, but not be able to
refer to the constant "as is"??

Why should I even bother with all these, since I am using only 1 package
MyPackage? The documentation says package is namespace is symbol table.
Why does MY_FIRST_CONSTANT work "as is" in, and not in

I am using Perl v5.8.8.


======================================================================= . My PGP key fingerprint is:
9D25 3D89 75F1 DF1D F434  25D7 E87F A1B9 B80F 8062
Version: GnuPG v1.4.7 (GNU/Linux)
Comment: Using GnuPG with Fedora -


Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About