Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 525
Anudeepa Avatar asked Jun 09 '21 08:06

Anudeepa


People also ask

Can constants value change?

A constant is a data item whose value cannot change during the program's execution. Thus, as its name implies – the value is constant.

How to declare constant in Perl?

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' .


2 Answers

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;
}
like image 82
choroba Avatar answered Nov 15 '22 06:11

choroba


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;
like image 23
ikegami Avatar answered Nov 15 '22 07:11

ikegami