{
    "mode": "perldoc",
    "parameter": "constant",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/constant/json",
    "generated": "2026-12-06T20:45:57Z",
    "synopsis": "use constant PI    => 4 * atan2(1, 1);\nuse constant DEBUG => 0;\nprint \"Pi equals \", PI, \"...\\n\" if DEBUG;\nuse constant {\nSEC   => 0,\nMIN   => 1,\nHOUR  => 2,\nMDAY  => 3,\nMON   => 4,\nYEAR  => 5,\nWDAY  => 6,\nYDAY  => 7,\nISDST => 8,\n};\nuse constant WEEKDAYS => qw(\nSunday Monday Tuesday Wednesday Thursday Friday Saturday\n);\nprint \"Today is \", (WEEKDAYS)[ (localtime)[WDAY] ], \".\\n\";",
    "sections": {
        "NAME": {
            "content": "constant - Perl pragma to declare constants\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use constant PI    => 4 * atan2(1, 1);\nuse constant DEBUG => 0;\n\nprint \"Pi equals \", PI, \"...\\n\" if DEBUG;\n\nuse constant {\nSEC   => 0,\nMIN   => 1,\nHOUR  => 2,\nMDAY  => 3,\nMON   => 4,\nYEAR  => 5,\nWDAY  => 6,\nYDAY  => 7,\nISDST => 8,\n};\n\nuse constant WEEKDAYS => qw(\nSunday Monday Tuesday Wednesday Thursday Friday Saturday\n);\n\nprint \"Today is \", (WEEKDAYS)[ (localtime)[WDAY] ], \".\\n\";\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This pragma allows you to declare constants at compile-time.\n\nWhen you declare a constant such as \"PI\" using the method shown above, each machine your script\nruns upon can have as many digits of accuracy as it can use. Also, your program will be easier\nto read, more likely to be maintained (and maintained correctly), and far less likely to send a\nspace probe to the wrong planet because nobody noticed the one equation in which you wrote\n3.14195.\n\nWhen a constant is used in an expression, Perl replaces it with its value at compile time, and\nmay then optimize the expression further. In particular, any code in an \"if (CONSTANT)\" block\nwill be optimized away if the constant is false.\n",
            "subsections": []
        },
        "NOTES": {
            "content": "As with all \"use\" directives, defining a constant happens at compile time. Thus, it's probably\nnot correct to put a constant declaration inside of a conditional statement (like \"if ($foo) {\nuse constant ... }\").\n\nConstants defined using this module cannot be interpolated into strings like variables. However,\nconcatenation works just fine:\n\nprint \"Pi equals PI...\\n\";        # WRONG: does not expand \"PI\"\nprint \"Pi equals \".PI.\"...\\n\";    # right\n\nEven though a reference may be declared as a constant, the reference may point to data which may\nbe changed, as this code shows.\n\nuse constant ARRAY => [ 1,2,3,4 ];\nprint ARRAY->[1];\nARRAY->[1] = \" be changed\";\nprint ARRAY->[1];\n\nConstants belong to the package they are defined in. To refer to a constant defined in another\npackage, specify the full package name, as in \"Some::Package::CONSTANT\". Constants may be\nexported by modules, and may also be called as either class or instance methods, that is, as\n\"Some::Package->CONSTANT\" or as \"$obj->CONSTANT\" where $obj is an instance of \"Some::Package\".\nSubclasses may define their own constants to override those in their base class.\n\nAs of version 1.32 of this module, constants can be defined in packages other than the caller,\nby including the package name in the name of the constant:\n\nuse constant \"OtherPackage::FWIBBLE\" => 7865;\nconstant->import(\"Other::FWOBBLE\",$value); # dynamically at run time\n\nThe use of all caps for constant names is merely a convention, although it is recommended in\norder to make constants stand out and to help avoid collisions with other barewords, keywords,\nand subroutine names. Constant names must begin with a letter or underscore. Names beginning\nwith a double underscore are reserved. Some poor choices for names will generate warnings, if\nwarnings are enabled at compile time.\n",
            "subsections": [
                {
                    "name": "List constants",
                    "content": "Constants may be lists of more (or less) than one value. A constant with no values evaluates to\n\"undef\" in scalar context. Note that constants with more than one value do *not* return their\nlast value in scalar context as one might expect. They currently return the number of values,\nbut this may change in the future. Do not use constants with multiple values in scalar context.\n\nNOTE: This implies that the expression defining the value of a constant is evaluated in list\ncontext. This may produce surprises:\n\nuse constant TIMESTAMP => localtime;                # WRONG!\nuse constant TIMESTAMP => scalar localtime;         # right\n\nThe first line above defines \"TIMESTAMP\" as a 9-element list, as returned by localtime() in list\ncontext. To set it to the string returned by localtime() in scalar context, an explicit \"scalar\"\nkeyword is required.\n\nList constants are lists, not arrays. To index or slice them, they must be placed in\nparentheses.\n\nmy @workdays = WEEKDAYS[1 .. 5];            # WRONG!\nmy @workdays = (WEEKDAYS)[1 .. 5];          # right\n"
                },
                {
                    "name": "Defining multiple constants at once",
                    "content": "Instead of writing multiple \"use constant\" statements, you may define multiple constants in a\nsingle statement by giving, instead of the constant name, a reference to a hash where the keys\nare the names of the constants to be defined. Obviously, all constants defined using this method\nmust have a single value.\n\nuse constant {\nFOO => \"A single value\",\nBAR => \"This\", \"won't\", \"work!\",        # Error!\n};\n\nThis is a fundamental limitation of the way hashes are constructed in Perl. The error messages\nproduced when this happens will often be quite cryptic -- in the worst case there may be none at\nall, and you'll only later find that something is broken.\n\nWhen defining multiple constants, you cannot use the values of other constants defined in the\nsame declaration. This is because the calling package doesn't know about any constant within\nthat group until *after* the \"use\" statement is finished.\n\nuse constant {\nBITMASK => 0xAFBAEBA8,\nNEGMASK => ~BITMASK,                    # Error!\n};\n"
                },
                {
                    "name": "Magic constants",
                    "content": "Magical values and references can be made into constants at compile time, allowing for way cool\nstuff like this. (These error numbers aren't totally portable, alas.)\n\nuse constant E2BIG => ($! = 7);\nprint   E2BIG, \"\\n\";        # something like \"Arg list too long\"\nprint 0+E2BIG, \"\\n\";        # \"7\"\n\nYou can't produce a tied constant by giving a tied scalar as the value. References to tied\nvariables, however, can be used as constants without any problems.\n"
                }
            ]
        },
        "TECHNICAL NOTES": {
            "content": "In the current implementation, scalar constants are actually inlinable subroutines. As of\nversion 5.004 of Perl, the appropriate scalar constant is inserted directly in place of some\nsubroutine calls, thereby saving the overhead of a subroutine call. See \"Constant Functions\" in\nperlsub for details about how and when this happens.\n\nIn the rare case in which you need to discover at run time whether a particular constant has\nbeen declared via this module, you may use this function to examine the hash\n%constant::declared. If the given constant name does not include a package name, the current\npackage is used.\n\nsub declared ($) {\nuse constant 1.01;              # don't omit this!\nmy $name = shift;\n$name =~ s/^::/main::/;\nmy $pkg = caller;\nmy $fullname = $name =~ /::/ ? $name : \"${pkg}::$name\";\n$constant::declared{$fullname};\n}\n",
            "subsections": []
        },
        "CAVEATS": {
            "content": "List constants are not inlined unless you are using Perl v5.20 or higher. In v5.20 or higher,\nthey are still not read-only, but that may change in future versions.\n\nIt is not possible to have a subroutine or a keyword with the same name as a constant in the\nsame package. This is probably a Good Thing.\n\nA constant with a name in the list \"STDIN STDOUT STDERR ARGV ARGVOUT ENV INC SIG\" is not allowed\nanywhere but in package \"main::\", for technical reasons.\n\nUnlike constants in some languages, these cannot be overridden on the command line or via\nenvironment variables.\n\nYou can get into trouble if you use constants in a context which automatically quotes barewords\n(as is true for any subroutine call). For example, you can't say $hash{CONSTANT} because\n\"CONSTANT\" will be interpreted as a string. Use $hash{CONSTANT()} or $hash{+CONSTANT} to prevent\nthe bareword quoting mechanism from kicking in. Similarly, since the \"=>\" operator quotes a\nbareword immediately to its left, you have to say \"CONSTANT() => 'value'\" (or simply use a comma\nin place of the big arrow) instead of \"CONSTANT => 'value'\".\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "Readonly - Facility for creating read-only scalars, arrays, hashes.\n\nAttribute::Constant - Make read-only variables via attribute\n\nScalar::Readonly - Perl extension to the \"SvREADONLY\" scalar flag\n\nHash::Util - A selection of general-utility hash subroutines (mostly to lock/unlock keys and\nvalues)\n",
            "subsections": []
        },
        "BUGS": {
            "content": "Please report any bugs or feature requests via the perlbug(1) utility.\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "Tom Phoenix, <rootbeer@redcat.com>, with help from many other folks.\n\nMultiple constant declarations at once added by Casey West, <casey@geeknest.com>.\n\nDocumentation mostly rewritten by Ilmari Karonen, <perl@itz.pp.sci.fi>.\n\nThis program is maintained by the Perl 5 Porters. The CPAN distribution is maintained by\nSébastien Aperghis-Tramoni <sebastien@aperghis.net>.\n\nCOPYRIGHT & LICENSE\nCopyright (C) 1997, 1999 Tom Phoenix\n\nThis module is free software; you can redistribute it or modify it under the same terms as Perl\nitself.\n",
            "subsections": []
        }
    },
    "summary": "constant - Perl pragma to declare constants",
    "flags": [],
    "examples": [],
    "see_also": []
}