Recently, I had an interesting concept pop into my mind. Is it possible to use constants as package methods, and if so, is there any compelling reason why people don't do that more often? A little research showed me that yes, it is possible to use constants as package methods, so now I open the question up to my fellow monks:

Is it a BAD THING(tm) to use constants as package methods?

Pros:

Cons:

Example:

test.pl
#!perl use strict; use warnings; use My::Package; use My::Package::Derived; local $\ = "\n"; my $item1 = new My::Package; my $item2 = new My::Package::Derived; print $item1->SOME_VALUE; print $item1->SOME_DERIVED_VALUE; print $item1->ANOTHER_DERIVED_VALUE; print '-' x 30; print $item2->SOME_VALUE; print $item2->SOME_DERIVED_VALUE; print $item2->ANOTHER_DERIVED_VALUE;
My/Package.pm
package My::Package; use strict; use warnings; use constant SOME_VALUE => 12; use constant SOME_DERIVED_VALUE => 14; use constant ANOTHER_DERIVED_VALUE => 21; sub new { bless {}, ref($_[0]) || $_[0]; } 1;
Derived.pm
package My::Package::Derived; use strict; use warnings; use My::Package; our (@ISA) = qw[My::Package]; use constant SOME_DERIVED_VALUE => 15; sub ANOTHER_DERIVED_VALUE() { int(rand(100)+1); } 1;

References

2002-03-13 Edit by Corion : Fixed title (almost) per request


In reply to Is it morally wrong to use constants as methods in a package? by johannz

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.