constant(3pm)

πŸ’– constant(3pm) πŸ’–

okay so bestie, welcome to constant, straight out of the Perl Programmers Reference Guide (that's the 3pm part, mwah). it's a pragma, it's iconic, it lets you declare constants at compile time, and honestly? it's giving "stop hardcoding numbers in your code" energy. let's get into it 🫢


✨ NAME ✨

constant β€” the Perl pragma for declaring constants. periodt.


πŸŽ€ 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 bestie, compile time, not run time. look at that speed πŸ’…

when you declare a constant like PI using the method up there, every machine your script runs on gets as many digits of accuracy as it can actually use. which is slay. and also: your program becomes easier to read, way more likely to be maintained (and maintained correctly, which is the whole point), and far less likely to send a space probe to the wrong planet because literally nobody noticed that one equation where you wrote 3.14195. 😭 that's a real fear. that's the fear.

when a constant is used in an expression, Perl replaces it with its value at compile time, and then may optimize the expression even further. specifically: any code inside an if (CONSTANT) block gets optimized away if the constant is false. gone. not even there. πŸ’€


🌸 NOTES 🌸

like with 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 ... }. just… don't do that, bestie πŸ™ˆ

constants defined with this module cannot be interpolated into strings like variables can. but concatenation? concatenation works just fine:

    print "Pi equals PI...\n";        # WRONG: does not expand "PI"
    print "Pi equals ".PI."...\n";    # right

even though a reference can be declared as a constant, that reference may point to data that can totally still be changed. look:

    use constant ARRAY => [ 1,2,3,4 ];
    print ARRAY->[1];
    ARRAY->[1] = " be changed";
    print ARRAY->[1];

so like, the constant is constant, the stuff inside said "nah". πŸ’€

constants belong to the package they're defined in. if you wanna refer to a constant defined in another package, you type out the full package name, like Some::Package::CONSTANT. constants may be exported by modules, and they may also be called as either class or instance methods β€” that means as Some::Package->CONSTANT, or as $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 make it constants πŸ‘‘

as of version 1.32 of this module, constants can be defined in packages other than the caller, by including the package name in the name of the constant:

    use constant "OtherPackage::FWIBBLE" => 7865;
    constant->import("Other::FWOBBLE",$value); # dynamically at run time

the ALL CAPS thing for constant names is merely a convention β€” but it's a recommended one, because it makes constants stand out and helps you avoid collisions with other barewords, keywords, and subroutine names. constant names must begin with a letter or an underscore. names beginning with a double underscore are reserved. and some poor choices for names will generate warnings, if warnings are enabled at compile time. so like, choose wisely ✨

πŸ“ List constants πŸ“

constants may be lists of more (or less) than one value. 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 might expect. right now they return the number of values, but that may change in the future. so do not use constants with multiple values in scalar context. fr fr, don't.

NOTE: this implies that the expression defining the value of a constant is evaluated in list context. which may produce surprises:
    use constant TIMESTAMP => localtime;                # WRONG!
    use constant TIMESTAMP => scalar localtime;         # right

the first line defines TIMESTAMP as a 9-element list, as returned by localtime() in list context. to set it to the string returned by localtime() in scalar context, you need an explicit scalar keyword. the more you know 🌈

list constants are lists, not arrays. to index or slice them, they must be placed in parentheses:

    my @workdays = WEEKDAYS[1 .. 5];            # WRONG!
    my @workdays = (WEEKDAYS)[1 .. 5];          # right

πŸ’œ Defining multiple constants at once πŸ’œ

instead of writing a million separate use constant statements, you can define multiple constants in a single statement β€” you just give a reference to a hash instead of the constant name, where the keys are the names of the constants you wanna define. obviously, all constants defined this way must have a single value.

    use constant {
        FOO => "A single value",
        BAR => "This", "won't", "work!",        # Error!
    };

this is a fundamental limitation of how hashes get constructed in Perl. and the error messages you get when this happens are often quite cryptic β€” in the worst case there may be none at all, and you'll only find out later that something is broken. 😭 not the silent failure.

also, when you're defining multiple constants, you cannot use the values of other constants defined in that same declaration. why? because the calling package doesn't know about any constant in that group until after the use statement finishes. rude, but that's how it is.

    use constant {
        BITMASK => 0xAFBAEBA8,
        NEGMASK => ~BITMASK,                    # Error!
    };

🧚 Magic constants 🧚

magical values and references can be made into constants at compile time, which allows for 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"

you can't produce a tied constant by giving a tied scalar as the value, no cap. references to tied variables, though? those can be used as constants without any problems. 🫢


⭐ 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 you the overhead of a subroutine call. see "Constant Functions" in perlsub for the details on how and when this happens. iykyk.

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};
    }

(and yes bestie, do NOT omit that use constant 1.01; line, it's literally commented in the source πŸ™ˆ)


πŸ’€ CAVEATS πŸ’€

  • list constants are not inlined unless you're on Perl v5.20 or higher. and in v5.20 or higher they're still not read-only, but that may change in future versions. so like, watch this space πŸ‘€
  • you can't have a subroutine or a keyword with the same name as a constant in the same package. which is probably a Good Thing, honestly.
  • a constant with a name in the list STDIN STDOUT STDERR ARGV ARGVOUT ENV INC SIG is not allowed anywhere except 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 that automatically quotes barewords (which is true for any subroutine call). 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. similarly, since the => operator quotes a bareword immediately to its left, you have to say CONSTANT() => 'value' (or just use a comma in place of the big arrow) instead of CONSTANT => 'value'. big arrow betrayal 😭

πŸ”₯ SEE ALSO πŸ”₯

  • Readonly β€” Facility for creating read-only scalars, arrays, hashes.
  • Attribute::Constant β€” Make read-only variables via attribute
  • Scalar::Readonly β€” Perl extension to the SvREADONLY scalar flag
  • Hash::Util β€” A selection of general-utility hash subroutines (mostly to lock/unlock keys and values)

πŸ› BUGS πŸ›

please report any bugs or feature requests via the perlbug(1) utility. the porters wanna hear from you, 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 (C) 1997, 1999 Tom Phoenix

This module is free software; you can redistribute it or modify it under the same terms as Perl itself.


okay that's the whole page, bestie, you ate πŸ’… oh and btw β€” this one's from perl v5.42.3, dated 2026-11-03, and it's the constant(3pm) page, so you know exactly where to find it again. mwah πŸ«Άβœ¨πŸŽ€

πŸ“¦ where this page comes from