← All languages
Perl construct of the day
Random

use constant

Declare named constants.

Description

The use constant pragma creates compile-time constants. Once defined, a constant cannot be modified. Constants are implemented as subroutines with no arguments that return a fixed value.

Multiple constants can be defined in a single use constant statement by passing a hash reference. Constants are useful for giving meaningful names to magic numbers and configuration values.

Because constants are implemented as subroutines, they do not interpolate directly in double-quoted strings. Use concatenation or a temporary variable instead.

Example

use constant PI => 3.14159265;
use constant MAX_SIZE => 1024;

print "Pi is approximately ", PI, "\n";

# Multiple constants
use constant {
  RED   => 1,
  GREEN => 2,
  BLUE  => 3,
};

Reference