in reply to How do I initiate a constant with variable value?

It seems like a simpler and more natural approach would be to define a getter in the module, a la

my $someVar = "someValue"; sub get_cnst { return $someVar; }

In this way, the variable is readable but not writable from outside the module. Is there a particular reason it needs to be a simple scalar?

Replies are listed 'Best First'.
Re^2: How do I initiate a constant with variable value?
by accessdenied (Acolyte) on Jun 04, 2010 at 13:53 UTC

    Tried so many times so I forgot to mention additional requirements, sorry.

    I don't like using getter because there are several scripts which uses module and several modules also, so number of getters and calls to them becomes big. Calls costs time and my task is optimisation so I would like to avoid getters.

    By the way, I found that constants in Perl actually implemented by subs, so each mention of constant is actually call to sub which returns value. As for me this looks like having getters. So, looks like I don't need constants really. I need some way to define readonly object without use of additional modules and other time-spending things.

      If you want it to be initialized once at run time and universally accessible for the remainder of the script's life, you could also accomplish this using a closure:

      #!/usr/bin/perl use strict; use warnings; sub definer { my $value = shift; sub outputter { no warnings "closure"; print "$value\n"; } } definer(5); outputter(); definer(6); outputter();

      If you are optimizing, do some profiling first to make sure that you are actually optimizing where it is needed - check out Devel::NYTProf. If you are worried about overhead introduced by function calls, it's possible Perl is not the best tool for this job or that you should delve into perlxs. But profile first and often.

      How does a module cost you time? I really doubt that you have profiled your script to determine that using modules is what costs you time.

        Each module contains some code and also some init code which is executed when module "used". Doesn't this cost time?

        Of couse this is not the only one place, I did some profiling and is was the reason why I started thinking about constants since there are so many places with getters and similar things.