Good development techniques usually indicate that one package should exist in one file.
Agreed, but what if I want to use those constants from a subclass, or in some other piece of code? More pre-processor trickery? Ick.
The Perl pragma constants are accessible at runtime, and can be exposed to other modules in a normal Perl fashion.
For those cases where 2+ packages should co-exist in one file, I have often found that I want the same constants for all the packages within a file. But, I have to do things like Parent::SOME_CONSTANT instead of just SOME_CONSTANT, for that specific reason.
One technique you might find applicable is to define a constant and then export it to your other modules, the same way you would if they were spread out over multiple files:
package MyFlags;
use constant FooFlag => 42;
use constant BarFlag => 23;
use base 'Exporter';
BEGIN { @MyFlags::EXPORT_OK = qw( FooFlag BarFlag ); }
BEGIN { $::INC{'MyFlags.pm'} ||= __FILE__; }
package MyWidgetFactory;
use MyFlags qw( FooFlag );
print FooFlag . "\n";
package MyFlyingMonkey;
use MyFlags qw( FooFlag BarFlag );
print BarFlag . "\n";
If I want to associate tuber-ness with Potatoes vs. Peaches, I would make it accessible via some method. So, instead of Potato::tuber, I would have Potato->is_tuber, or some such.
Sure, by all means, go ahead and treat it as a method; after all, use constant is mostly just shorthand for making simple subroutines:
package Potato;
use constant tuber => 1;
package main;
print Potato->tuber;
Constant references to hashes/arrays don't seem to have a huge benefit.
Agreed, there's no breakthrough here -- just some syntactic sweetener... If your module's interface features a lot of public methods and only a couple of public package variables, it can be attractive to wrap those references in constant subs.
This is a completely new feature of Perl to me, and one that seems to have huge benefits.
Yup; both the CPP #defines and Perl constants are useful tools, each with their own ups and downs; I hope this post has clarified why, if given the choice, I'd typically use constant. |