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

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.

  • Comment on Re^2: How do I initiate a constant with variable value?

Replies are listed 'Best First'.
Re^3: How do I initiate a constant with variable value?
by kennethk (Abbot) on Jun 04, 2010 at 13:58 UTC
    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.

Re^3: How do I initiate a constant with variable value?
by Corion (Patriarch) on Jun 04, 2010 at 13:56 UTC

    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.

        If you're worrying about whether loading a module costs time, then you're looking at the wrong locations:

        1. If your program runs a long time, then loading a module has a neglibile portion of the cost and optimizing that away gains you little opposed to the overall runtime of the program.
        2. If your program runs a short time but very often, then you should look at how to make your program run a longer time and process multiple requests. This will save you the loading and initialization time.
        3. If you're still worrying about the time that loading an external file might take, then Perl is the wrong approach.