I have a bunch of Perl files which take in some filename constants. I would like to define these in a separate file - something like a header file in C. What's the best/most standard way of doing this in Perl?
Use $hash{CONSTANT()} or $hash{+CONSTANT} to prevent the bareword quoting mechanism from kicking in. Similarly, since the => operator quotes a bareword immediately to its left, you have to say CONSTANT() => 'value' (or simply use a comma in place of the big arrow) instead of CONSTANT => 'value' .
Even if constants are related, they should not be put into a single file. The wrapper classes in Java is a good example of related constants being defined in their own class files rather than in a WrapperConstants file.
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.
There is no equivalent to C header files in Perl. To declare and define global constants, you can use the define pragma. I have no experience with this module although the interface seems sensible.
On the other hand, you can write a module where you define constants and import them into your module using use
. For example:
package MyConstants;
use strict; use warnings;
use Exporter qw( import );
use Const::Fast;
our @EXPORT = qw();
our @EXPORT_OK = qw( $X $Y );
const our $X => 'this is X';
const our $Y => 'this is Y';
__PACKAGE__;
__END__
You can then use this module as follows:
#!/usr/bin/perl
use strict; use warnings;
use MyConstants qw( $X );
print "$X\n";
print "$MyConstants::Y\n";
If you are OK with using fully qualified variable names (e.g. $MyConstants::Y
), you do not need Exporter
at all.
Also, make sure variables you export are not modifiable elsewhere (see the caution in Exporter
docs).
Of course, you could also define constants using constant.pm. It may be faster to use such constants, but they are awkward if you need to interpolate them in a string.
We usually do this with a module name Constants. Something like:
package MyPackage::Constants;
our $DIR = "/home/chriss";
our $MAX_FILES = 5;
1;
Then, to use it:
package MyPackage;
use MyPackage::Constants;
open(my $fh, ">", $MyPackage::Constants::DIR . "/file");
If you didn't want to reference the package all the time, you could use Exporter and bring in all the symbols you want.
This sounds like configuration settings, which would be better put in a config file that you parse with one of the various CPAN modules, for instance Config::Any.
Configuration is data, which IMO shouldn't be in your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With