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?
One way would be to write them as a perl module, that you can subsequently include with "require" or "use". You'd write your file like this -- give it a .pm extension (e.g., myFabulousPackage.pm)
package myFabulousPackage;
$someSetting=45;
$otherSetting='Fish';
1;
Then in your perl script, this would include the file and then reference $otherSetting:
#!/usr/bin/perl
use myFabulousPackage;
print $myFabulousPackage::otherSetting;
This is just a very simple view of what you can do with a package/module, but for what you need, this might be the simplest way to implement it. Similarly, you can put sub's in the package as well, and reference them in a similar way.
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.
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 base 'Exporter';
use Readonly;
our @EXPORT = qw();
our @EXPORT_OK = qw( $X $Y );
Readonly::Scalar our $X => 'this is X';
Readonly::Scalar our $Y => 'this is Y';
1;
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 is faster to use such constants, but they are awkward if you need to interpolate them in a string.