Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize constant variable with perl

Tags:

perl

I have the following constant :

use constant => 7

is there an option to set the constant by a scalar variable once and then the value of the constant will be the initialized value i.e somthing like this :

use constant => $scalar -> then the constant from now have the value of scalar on this point

any suggestion ?

like image 714
smith Avatar asked Jan 22 '26 09:01

smith


2 Answers

Constants created with use constant are processed at compile time, so that $scalar variable will likely not have any value assigned yet.

You can however use the Const::Fast module to make a scalar – well – constant:

use Const::Fast;

my $scalar = 7;
const my $constant => $scalar;
$constant = 42; # dies

This is preferable to use constant anyway as it's nicer to handle const scalars than it is to handle constants (which are implemented as special subroutines). For example, a const scalar can be interpolated into a string.

However, compile-time constants take part in the constant folding optimization. There are some cases where this is actually necessary, so some use for use constant remains.

(If you can't use Const::Fast, then Readonly is another option, although slower)

like image 81
amon Avatar answered Jan 25 '26 20:01

amon


Yes, you can. Of course, you must assign the value to the scalar soon enough.

my $foo;
BEGIN {
   ...
   ...
   $foo = ...;
}
use constant FOO => $foo;

You could also use do.

use constant FOO => do {
   ...
   ...
   ...
};
like image 42
ikegami Avatar answered Jan 25 '26 20:01

ikegami