http://www.perlmonks.org?node_id=895873


in reply to Using constant to override (abstract) methods.

The more important issue to me is why?

Although your approach 'works', I should think the use of 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).

Second, use constant is not the obvious place to look for a method that overrides a superclass method.

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 use constant are not final. They can be overridden by any subclass because they are, after all subs. For example,

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

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 Constant Functions:

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 & .

There is nothing special about use constant. You can see the source code for the use constant pragma here. It is just Perl code that converts use constant X => Y into  sub X() { Y }. If anything, you are adding overhead to your startup code as compared with a simple sub definition since the pragma has to analyze each X => Y and generate the necessary symbols.

Update: added comments about performance.