Anudeepa
Anudeepa

Reputation: 716

Is there any way to change the value of constant in Perl?

use constant TESTVERSION => 2;

In my code, I want to change the value of the constant based on some check. If the condition is true, I should use same TESTVERSION and if false, I have to use some different version. Is it possible in perl to update the constant value at run time?

Upvotes: 6

Views: 409

Answers (3)

Joe Casadonte
Joe Casadonte

Reputation: 16889

If you need run-time definition of constant values, then I would suggest using something other than the contant pragma. Overriding the subroutine will be confusing to future maintainers, IMO. I've personally never liked it because of the syntax restrictions (e.g. lack of string interpolation).

For small scripts, I use a coding standing: I define them in their own section, and give them names in ALL CAPS. Yes, that relies on people not violating the standard as it's not enforced/enforceable. I mostly work with professionals and we have mandatory code reviews, so it's never been a problem.

For larger projects, I use the Readonly module. It's old, but it works for me.

For more options and discussion, see an old-ish blog post by Gabor Szabo: Constants and read-only variables in Perl

Upvotes: 0

ikegami
ikegami

Reputation: 386666

No, a constant has to be defined at compile-time (or at least before the code using is compiled). But nothing stops you from doing your check at compile-time.

use constant TESTVERSION => cond() ? 2 : 3;

or

sub test_version {
   return cond() ? 2 : 3;
}

use constant TESTVERSION => test_version();

or

my $test_version;
BEGIN {
   $test_version = cond() ? 2 : 3;
}

use constant TESTVERSION => $test_version;

Upvotes: 6

choroba
choroba

Reputation: 242333

constant behaves as a sub with empty prototypes that always returns the same value, so it can be inlined. Redefine it with a real subroutine.

use strict;
use warnings;
use feature 'say';

use constant TESTVERSION => 2;
my $TESTVERSION = TESTVERSION;
{   no warnings 'redefine';
    sub TESTVERSION() { $TESTVERSION }
}

for my $condition (0, 1) {
    $TESTVERSION = 3 if $condition;
    say TESTVERSION;
}

Upvotes: 7

Related Questions