Re: How to put a global variable in a package, accessible to users of that package?



Stewart Anderson wrote:
From: mrstevegross [mailto:mrstevegross@xxxxxxxxx]

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".

That looks interesting. How do people use that kind of constant
assignment. I can see uses for it, but would be interested to hear what
others use this technique for.

Take a look at

perldoc constant

What the pragma creates is a prototyped subroutine with exactly zero parameters,
so writing

use constant PI => 3.14159265359;

is equivalent to a subroutine

sub PI() {
3.14159265359;
}

However it has a few of advantages over just writing this directly:

- It is self-documenting, i.e. it is clear that a named constant is being
defined.

- The Perl compiler has a chance to optimise out the subroutine definition and
call

- The implementation could change to something more optimal in the future
without needing to alter any code that uses the pragma

I hope this helps,

Rob
.



Relevant Pages

  • Re: from __future__ import absolute_import ?
    ... foo not in bar ... A path below the package level is generally a good means to shoot ... to represent a python "package" structure. ...
    (comp.lang.python)
  • Re: A Question about DEFPACKAGE syntax
    ... Lisp and for not-really-Common-Lisp ... that it's easier to type:foo than to type "FOO". ... "FOO" does not create superficial symbols in the keyword package ...
    (comp.lang.lisp)
  • Re: Request for help constructing a simple macro
    ... Isn't an unbound symbol just a `symbol object'? ... Object in Lisp means generally all Lisp data. ... #:FOO ... No package for this symbol. ...
    (comp.lang.lisp)
  • Re: from __future__ import absolute_import ?
    ... foo not in bar ... Unfortunately this is a side effect of using the os's directory structure to represent a python "package" structure. ...
    (comp.lang.python)
  • Re: Best Practices - common code
    ... >> Let's say that we have a bunch of independent projects, among them Foo ... all of this common code ... > you can break up the bulk along package or package family* lines. ... > Ant can analyze class dependencies. ...
    (comp.lang.java.programmer)