note
ELISHEVA
<p>The more important issue to me is why?</p>
<p>Although your approach 'works', I should think the use of [doc://constant] to define overrides would be very confusing to future maintainers. For one, not everyone knows that constants are actually subs. Your coworker's confusion and many posts here I think testify to that. (look on Super Search).</p>
<p>Second, <c>use constant</c> is not the obvious place to look for a method that overrides a superclass method.</p>
<p>Third, it is somewhat misleading. The word "constant" implies immutable. That might lead someone to think that you have defined a final method. Perhaps that is even your reason for wanting to use "constant" this way? However, methods defined via <c>use constant</c> are not final. They can be overridden by any subclass because they are, after all subs. For example,</p>
<code>
use strict;
use warnings;
package Foo;
use constant X => 100;
sub new { bless([], $_[0]); }
package Goo;
our @ISA=qw(Foo);
use constant X => 200;
sub new { bless([], $_[0]); }
package MeToo;
our @ISA=qw(Foo);
sub X { print "Hello World\n"; }
my $oFoo = Foo->new();
my $oGoo = Goo->new();
my $oMeToo = MeToo->new();
print "$oFoo -> X = ", $oFoo->X, "\n";
print "$oGoo -> X = ", $oGoo->X, "\n";
$oMeToo->X();
#outputs
Foo=ARRAY(0x8218ed0) -> X = 100
Goo=ARRAY(0x8218f10) -> X = 200
Hello World
</code>
<p>Performance wouldn't be a reason to use constants in this way either. Perl optimizes constant methods even when they are not explicitly defined as constants. According to [doc://perlsub#Constant-Functions]:</p>
<blockquote><i>
Functions with a prototype of () are potential candidates for inlining. If the result after optimization and constant folding is either a constant or a lexically-scoped scalar which has no other references, then it will be used in place of function calls made without & .
</i></blockquote>
<p>There is nothing special about <c>use constant</c>. You can see the source code for the <c>use constant</c> pragma [http://cpansearch.perl.org/src/SAPER/constant-1.19/lib/constant.pm|here]. It is just Perl code that converts <c>use constant X => Y</c> into <c> sub X() { Y }</c>. If anything, you are adding overhead to your startup code as compared with a simple sub definition since the pragma has to analyze each <c>X => Y</c> and generate the necessary symbols.</p>
<p><b>Update:</b> added comments about performance.</p>
895863
895863