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?
A constant is a data item whose value cannot change during the program's execution. Thus, as its name implies – the value is constant.
Use $hash{CONSTANT()} or $hash{+CONSTANT} to prevent the bareword quoting mechanism from kicking in. Similarly, since the => operator quotes a bareword immediately to its left, you have to say CONSTANT() => 'value' (or simply use a comma in place of the big arrow) instead of CONSTANT => 'value' .
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;
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With