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 ?
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)
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 {
...
...
...
};
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