constant(3perl)
๐ NAME ๐
okay so bestie, meet constant โ the Perl pragma that lets you declare constants. โจ That's it, that's the whole vibe. It lives in the Perl Programmers Reference Guide, and it's about to make your code so much cuter and so much safer. ๐
๐ SYNOPSIS ๐
use constant PI => 4 * atan2(1, 1);
use constant DEBUG => 0;
print "Pi equals ", PI, "...\n" if DEBUG;
use constant {
SEC => 0,
MIN => 1,
HOUR => 2,
MDAY => 3,
MON => 4,
YEAR => 5,
WDAY => 6,
YDAY => 7,
ISDST => 8,
};
use constant WEEKDAYS => qw(
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
);
print "Today is ", (WEEKDAYS)[ (localtime)[WDAY] ], ".\n";
๐ธ DESCRIPTION ๐ธ
This pragma lets you declare constants at compile-time. Yes, compile-time. It's giving responsible main character energy. ๐
When you declare a constant like "PI" using the method shown above, each machine your script runs on can have as many digits of accuracy as it can use. ๐งฎ Also, your program will be easier to read, more likely to be maintained (and maintained correctly ๐ญ), and far less likely to send a space probe to the wrong planet because nobody noticed the one equation in which you wrote 3.14195. Like. That's not a hypothetical bestie. Not me crying over a typo in a rocket's math. ๐๐
When a constant gets used in an expression, Perl replaces it with its value at compile time, and may then optimize the expression even further. In particular, any code inside an if (CONSTANT) block will be optimized away entirely if the constant is false. Poof. Gone. Iconic. โจ
๐ NOTES ๐
Same rules as all "use" directives: defining a constant happens at compile time. So it's probably not correct to put a constant declaration inside a conditional statement (like if ($foo) { use constant ... }). It doesn't work the way your brain wants it to. ๐
Constants defined with this module cannot be interpolated into strings like variables can. But concatenation? Concatenation works just fine, no cap:
print "Pi equals PI...\n"; # WRONG: does not expand "PI"
print "Pi equals ".PI."...\n"; # right
Even if a reference gets declared as a constant, the reference can point at data that can still be changed โ look at this lil nightmare fuel:
use constant ARRAY => [ 1,2,3,4 ];
print ARRAY->[1];
ARRAY->[1] = " be changed";
print ARRAY->[1];
Constants belong to the package they're defined in. Want one from another package? Say the whole full package name, like "Some::Package::CONSTANT". Constants can be exported by modules, and can also be called as either class or instance methods โ that's "Some::Package->CONSTANT" or "$obj->CONSTANT", where $obj is an instance of "Some::Package". And subclasses may define their own constants to override the ones in their base class. Inheritance but for constants, slay. ๐
As of version 1.32 of this module, constants can be defined in packages other than the caller, just by putting the package name in the name of the constant:
use constant "OtherPackage::FWIBBLE" => 7865;
constant->import("Other::FWOBBLE",$value); # dynamically at run time
Using ALL CAPS for constant names is merely a convention โ but bestie, it's recommended. It makes constants stand out and helps you dodge collisions with other barewords, keywords, and subroutine names. Constant names must begin with a letter or underscore. Names beginning with a double underscore are reserved. And some truly poor choices for names will generate warnings, if warnings are enabled at compile time. ๐ฌ
๐ List constants
Constants can be lists of more than one value โ or less than one value, which is a whole concept. A constant with no values evaluates to "undef" in scalar context. And heads up: constants with more than one value do not return their last value in scalar context like you'd expect. They currently return the number of values, but that may change in the future. So yeah โ do not use constants with multiple values in scalar context. ๐ซ
NOTE: this implies that the expression defining the value of a constant is evaluated in list context. Which can produce surprises:
use constant TIMESTAMP => localtime; # WRONG!
use constant TIMESTAMP => scalar localtime; # right
That first line defines "TIMESTAMP" as a 9-element list, exactly what localtime() gives you in list context. If you wanted the string localtime() returns in scalar context, you have to say an explicit "scalar" keyword. No shortcuts. ๐
List constants are lists, not arrays. To index or slice them, you have to put them in parentheses:
my @workdays = WEEKDAYS[1 .. 5]; # WRONG!
my @workdays = (WEEKDAYS)[1 .. 5]; # right
๐ฆ Defining multiple constants at once
Instead of writing a million use constant statements, you can define multiple constants in one statement โ instead of the constant name, hand it a reference to a hash where the keys are the names of the constants you want defined. But obviously, all constants defined this way must have a single value. One. Uno. ๐ซถ
use constant {
FOO => "A single value",
BAR => "This", "won't", "work!", # Error!
};
This is a fundamental limitation of the way hashes are constructed in Perl. And the error messages when it happens are often extremely cryptic โ worst case, there might not be any error at all, and you'll only find out later that something is broken. Sneaky little gremlin behaviour. ๐
Also, when you're defining multiple constants, you cannot use the values of other constants defined in the same declaration. Why? Because the calling package doesn't know about any constant in that group until after the "use" statement finishes. Timeline problems, fr fr.
use constant {
BITMASK => 0xAFBAEBA8,
NEGMASK => ~BITMASK, # Error!
};
๐ Magic constants
Magical values and references can be made into constants at compile time, which unlocks way cool stuff like this. (These error numbers aren't totally portable, alas. ๐ญ)
use constant E2BIG => ($! = 7);
print E2BIG, "\n"; # something like "Arg list too long"
print 0+E2BIG, "\n"; # "7"
And one thing you can't do: you can't produce a tied constant by giving a tied scalar as the value. But references to tied variables can be used as constants without any problems whatsoever. ๐
๐ง TECHNICAL NOTES ๐ง
In the current implementation, scalar constants are actually inlinable subroutines. As of version 5.004 of Perl, the appropriate scalar constant gets inserted directly in place of some subroutine calls, saving the overhead of a subroutine call. Wanna know how and when that happens? See "Constant Functions" in perlsub for the details. ๐
In the rare case where you need to discover at run time whether a particular constant has been declared via this module, you can use this function to examine the hash %constant::declared. If the given constant name doesn't include a package name, the current package is used.
sub declared ($) {
use constant 1.01; # don't omit this!
my $name = shift;
$name =~ s/^::/main::/;
my $pkg = caller;
my $full_name = $name =~ /::/ ? $name : "${pkg}::$name";
$constant::declared{$full_name};
}
โ ๏ธ CAVEATS โ ๏ธ
Bestie. Read these. This is the part where things get spicy. ๐ถ๏ธ
- List constants are not inlined unless you are using Perl v5.20 or higher. And in v5.20 or higher, they're still not read-only โ but that may change in future versions. Future us problems. โจ
- It is not possible to have a subroutine or a keyword with the same name as a constant in the same package. This is probably a Good Thing. (It is. Trust.) ๐
- A constant with a name in the list
"STDIN STDOUT STDERR ARGV ARGVOUT ENV INC SIG"is not allowed anywhere but in package"main::", for technical reasons. Them's the rules. ๐ซ - Unlike constants in some languages, these cannot be overridden on the command line or via environment variables. Nope. Not happening. ๐
- You can get into trouble if you use constants in a context which automatically quotes barewords (this is true for any subroutine call, btw). For example, you can't say
$hash{CONSTANT}because"CONSTANT"will be interpreted as a string. Use$hash{CONSTANT()}or$hash{+CONSTANT}to stop the bareword quoting mechanism from kicking in. Same energy with the"=>"operator โ since it quotes a bareword immediately to its left, you have to say"CONSTANT() => 'value'"(or just use a comma instead of the big arrow) rather than"CONSTANT => 'value'". Write that down bestie. ๐
๐ SEE ALSO ๐
Readonly- Facility for creating read-only scalars, arrays, hashes.Attribute::Constant- Make read-only variables via attributeScalar::Readonly- Perl extension to the"SvREADONLY"scalar flagHash::Util- A selection of general-utility hash subroutines (mostly to lock/unlock keys and values)
๐ BUGS ๐
Found a bug? Got a feature request? Please report it via the perlbug(1) utility. They wanna hear it, fr fr. ๐ซถ
๐ AUTHORS ๐
Tom Phoenix, <rootbeer@redcat.com>, with help from many other folks.
Multiple constant declarations at once added by Casey West, <casey@geeknest.com>.
Documentation mostly rewritten by Ilmari Karonen, <perl@itz.pp.sci.fi>.
This program is maintained by the Perl 5 Porters. The CPAN distribution is maintained by Sรฉbastien Aperghis-Tramoni <sebastien@aperghis.net>.
๐ COPYRIGHT & LICENSE ๐
Copyright (C) 1997, 1999 Tom Phoenix
This module is free software; you can redistribute it or modify it under the same terms as Perl itself.
and that's the whole page bestie, you ate it, no crumbs left ๐ โ this was perl v5.44.0, dated 2026-10-17, so go forth and declare some constants, ily, bye ๐โจ๐ฆ
๐ฆ where this page comes from
- arch rolling: perl 5.44.0-1 ยท Artistic-1.0-Perl AND GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms