I've got a module where I precompile regexes for speed/later use. But I can't decide what's best practice in terms of how I handle these module constants.
package Foo::Bar; use Regexp::Assemble; our $VERSION = '0.01'; sub new { my $class = shift; my $self = bless({@_}, $class); ## precompile regexes $self->{regex} = Regexp::Assemble->new->add( 'some-stuff' )->re; return $self; } sub function { my $self; ... $var =~ $regex; }
vs.
package Foo::Bar; use Regexp::Assemble; our $VERSION = '0.01'; our $regex = Regexp::Assemble->new->add( 'some-stuff' )->re; sub function { ... $var =~ $regex; }

I don't hesitate to declare module wide constants within the on-load/BEGIN part of a module, but it somehow feels wrong when these constants require some computation on-load, like here, precompiling regexes.

I would favour the the latter version. Doing a clean OO-style init and having the $obj var around is a bit cumbersome for the simple module I'm working on.
Arg, noticed that? I used the word "clean" to describe having these 'constants' in $self...

So please Monks, give me some advice. Is it just a matter of style, or design priciples, or are there actual problematic things to consider when my constants do some computing on-load?

(One difference I can think of is that this computing introduces an overhead and with my decision I decide for the module user where the precompilation overhead ends up:
  "fast load" + "mandatory new(), slowed" + "fast method" -- OO-style
  vs.
  "slower load" + "no mandatory new()" + "fast method". -- on-load style

Anything except that?


In reply to Modules: computing a constant, "on load" or in new()? by isync

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.