Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use constants from a Perl module?

If I define a constant in a Perl module, how do I use that constant in my main program? (Or how do I call that constant in the main program?)

like image 672
PNMNS Avatar asked Oct 10 '08 21:10

PNMNS


People also ask

How do I use constants in Perl?

When a constant is used in an expression, Perl replaces it with its value at compile time, and may then optimize the expression further. In particular, any code in an if (CONSTANT) block will be optimized away if the constant is false.

How do you use constants?

You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.

What is use Perl?

In Perl, the use keyword is exactly equivalent to the following: use Mymodule; #is the same as BEGIN { require Mymodule; Mymodule->import(); } So if you are not defining an import routine in your code (or inheriting from Exporter ), then your modules are not importing anything into test.pl.


2 Answers

Constants can be exported just like other package symbols. Using the standard Exporter module, you can export constants from a package like this:

package Foo; use strict; use warnings;  use base 'Exporter';  use constant CONST => 42;  our @EXPORT_OK = ('CONST');  1; 

Then, in a client script (or other module)

use Foo 'CONST'; print CONST; 

You can use the %EXPORT_TAGS hash (see the Exporter documentation) to define groups of constants that can be exported with a single import argument.

Update: Here's an example of how to use the %EXPORT_TAGS feature if you have multiple constants.

use constant LARRY => 42; use constant CURLY => 43; use constant MOE   => 44;  our @EXPORT_OK = ('LARRY', 'CURLY', 'MOE'); our %EXPORT_TAGS = ( stooges => [ 'LARRY', 'CURLY', 'MOE' ] ); 

Then you can say

use Foo ':stooges'; print "$_\n" for LARRY, CURLY, MOE; 
like image 169
friedo Avatar answered Sep 19 '22 18:09

friedo


Constants are just subs with empty prototype, so they can be exported like any other sub.

# file Foo.pm package Foo; use constant BAR => 123; use Exporter qw(import); our @EXPORT_OK = qw(BAR);   # file main.pl: use Foo qw(BAR); print BAR; 
like image 20
moritz Avatar answered Sep 18 '22 18:09

moritz