On Thu, 2008-10-30 at 23:43 +0000, Rob Dixon wrote:
> mrstevegross wrote:
> >
> > I have a package named "Foo" in which I want to define some package-
> > level constants (such as $VAR="soemval"). I want those constants
> > available to users of package Foo, so the following code would work:
> > 
> > === foo.pl ===
> > package foo;
> > use constant VAR => "someval";
> > 
> > === bar.pl ===
> > use foo;
> > print $foo::VAR;
> > 
> > It doesn't appear to be working; it compiles ok, but it prints
> > nothing. I thought it would print "someval".
> 
> The code as you show it will not work at all. The line
> 
>   use foo;
> 
> will throw the error "Can't locate foo.pm in @INC" because you have 
> incorrectly
> named it foo.pl.
> 
> To get your program working, save the module as 'foo.pm' instead, and change 
> its
> contents to
> 
>   use strict;
>   use warnings;
> 
>   package foo;
> 
>   our $VAR = "someval";
> 
>   1;

Some additional notes:

1) The naming convention in Perl is to start packages and their file
with a capital letter.  Hence the file is Foo.pm and:

package Foo;

2) Perl does not have true constants.  When you `use constant` you
actually create a sub that returns a value.  This:

use constant VAR => "someval";

is the same as:

sub VAR {
  return "someval";
}

Since it is a sub, you can call it using a fully qualified name.  The
following call method is checked at compile time (and will give an error
if you misspell something):

use Foo;
Foo->VAR;

The following is checked at run time (and it will not give an error, if
any, until the code is executed):

use Foo;
Foo::VAR;

The compile time methodology is preferred.  Only use the run-time one if
you are dynamically creating subs.

3) You can download the module Readonly from CPAN
http://search.cpan.org/  It creates variables that cannot be changed.

4) Global 'my' variables cannot be accessed outside of the file their
are defined in.  They also cannot be exported via the Exporter module.
Define them with `our` or `use vars`.  All `our` globals can be accessed
with their fully qualified name, even if they are not exported.

See:
perldoc perlvar
perldoc perlmod
perldoc perlmodlib


-- 
Just my 0.00000002 million dollars worth,
  Shawn

The map is not the territory,
the dossier is not the person,
the model is not reality,
and the universe is indifferent to your beliefs.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to