1constant(3) User Contributed Perl Documentation constant(3)
2
3
4
6 constant - Perl pragma to declare constants
7
9 use constant PI => 4 * atan2(1, 1);
10 use constant DEBUG => 0;
11
12 print "Pi equals ", PI, "...\n" if DEBUG;
13
14 use constant {
15 SEC => 0,
16 MIN => 1,
17 HOUR => 2,
18 MDAY => 3,
19 MON => 4,
20 YEAR => 5,
21 WDAY => 6,
22 YDAY => 7,
23 ISDST => 8,
24 };
25
26 use constant WEEKDAYS => qw(
27 Sunday Monday Tuesday Wednesday Thursday Friday Saturday
28 );
29
30 print "Today is ", (WEEKDAYS)[ (localtime)[WDAY] ], ".\n";
31
33 This pragma allows you to declare constants at compile-time.
34
35 When you declare a constant such as "PI" using the method shown above,
36 each machine your script runs upon can have as many digits of accuracy
37 as it can use. Also, your program will be easier to read, more likely
38 to be maintained (and maintained correctly), and far less likely to
39 send a space probe to the wrong planet because nobody noticed the one
40 equation in which you wrote 3.14195.
41
42 When a constant is used in an expression, Perl replaces it with its
43 value at compile time, and may then optimize the expression further.
44 In particular, any code in an "if (CONSTANT)" block will be optimized
45 away if the constant is false.
46
48 As with all "use" directives, defining a constant happens at compile
49 time. Thus, it's probably not correct to put a constant declaration
50 inside of a conditional statement (like "if ($foo) { use constant ...
51 }").
52
53 Constants defined using this module cannot be interpolated into strings
54 like variables. However, concatenation works just fine:
55
56 print "Pi equals PI...\n"; # WRONG: does not expand "PI"
57 print "Pi equals ".PI."...\n"; # right
58
59 Even though a reference may be declared as a constant, the reference
60 may point to data which may be changed, as this code shows.
61
62 use constant ARRAY => [ 1,2,3,4 ];
63 print ARRAY->[1];
64 ARRAY->[1] = " be changed";
65 print ARRAY->[1];
66
67 Constants belong to the package they are defined in. To refer to a
68 constant defined in another package, specify the full package name, as
69 in "Some::Package::CONSTANT". Constants may be exported by modules,
70 and may also be called as either class or instance methods, that is, as
71 "Some::Package->CONSTANT" or as "$obj->CONSTANT" where $obj is an
72 instance of "Some::Package". Subclasses may define their own constants
73 to override those in their base class.
74
75 As of version 1.32 of this module, constants can be defined in packages
76 other than the caller, by including the package name in the name of the
77 constant:
78
79 use constant "OtherPackage::FWIBBLE" => 7865;
80 constant->import("Other::FWOBBLE",$value); # dynamically at run time
81
82 The use of all caps for constant names is merely a convention, although
83 it is recommended in order to make constants stand out and to help
84 avoid collisions with other barewords, keywords, and subroutine names.
85 Constant names must begin with a letter or underscore. Names beginning
86 with a double underscore are reserved. Some poor choices for names
87 will generate warnings, if warnings are enabled at compile time.
88
89 List constants
90 Constants may be lists of more (or less) than one value. A constant
91 with no values evaluates to "undef" in scalar context. Note that
92 constants with more than one value do not return their last value in
93 scalar context as one might expect. They currently return the number
94 of values, but this may change in the future. Do not use constants
95 with multiple values in scalar context.
96
97 NOTE: This implies that the expression defining the value of a constant
98 is evaluated in list context. This may produce surprises:
99
100 use constant TIMESTAMP => localtime; # WRONG!
101 use constant TIMESTAMP => scalar localtime; # right
102
103 The first line above defines "TIMESTAMP" as a 9-element list, as
104 returned by "localtime()" in list context. To set it to the string
105 returned by "localtime()" in scalar context, an explicit "scalar"
106 keyword is required.
107
108 List constants are lists, not arrays. To index or slice them, they
109 must be placed in parentheses.
110
111 my @workdays = WEEKDAYS[1 .. 5]; # WRONG!
112 my @workdays = (WEEKDAYS)[1 .. 5]; # right
113
114 Defining multiple constants at once
115 Instead of writing multiple "use constant" statements, you may define
116 multiple constants in a single statement by giving, instead of the
117 constant name, a reference to a hash where the keys are the names of
118 the constants to be defined. Obviously, all constants defined using
119 this method must have a single value.
120
121 use constant {
122 FOO => "A single value",
123 BAR => "This", "won't", "work!", # Error!
124 };
125
126 This is a fundamental limitation of the way hashes are constructed in
127 Perl. The error messages produced when this happens will often be
128 quite cryptic -- in the worst case there may be none at all, and you'll
129 only later find that something is broken.
130
131 When defining multiple constants, you cannot use the values of other
132 constants defined in the same declaration. This is because the calling
133 package doesn't know about any constant within that group until after
134 the "use" statement is finished.
135
136 use constant {
137 BITMASK => 0xAFBAEBA8,
138 NEGMASK => ~BITMASK, # Error!
139 };
140
141 Magic constants
142 Magical values and references can be made into constants at compile
143 time, allowing for way cool stuff like this. (These error numbers
144 aren't totally portable, alas.)
145
146 use constant E2BIG => ($! = 7);
147 print E2BIG, "\n"; # something like "Arg list too long"
148 print 0+E2BIG, "\n"; # "7"
149
150 You can't produce a tied constant by giving a tied scalar as the value.
151 References to tied variables, however, can be used as constants without
152 any problems.
153
155 In the current implementation, scalar constants are actually inlinable
156 subroutines. As of version 5.004 of Perl, the appropriate scalar
157 constant is inserted directly in place of some subroutine calls,
158 thereby saving the overhead of a subroutine call. See "Constant
159 Functions" in perlsub for details about how and when this happens.
160
161 In the rare case in which you need to discover at run time whether a
162 particular constant has been declared via this module, you may use this
163 function to examine the hash %constant::declared. If the given
164 constant name does not include a package name, the current package is
165 used.
166
167 sub declared ($) {
168 use constant 1.01; # don't omit this!
169 my $name = shift;
170 $name =~ s/^::/main::/;
171 my $pkg = caller;
172 my $full_name = $name =~ /::/ ? $name : "${pkg}::$name";
173 $constant::declared{$full_name};
174 }
175
177 List constants are not inlined unless you are using Perl v5.20 or
178 higher. In v5.20 or higher, they are still not read-only, but that may
179 change in future versions.
180
181 It is not possible to have a subroutine or a keyword with the same name
182 as a constant in the same package. This is probably a Good Thing.
183
184 A constant with a name in the list "STDIN STDOUT STDERR ARGV ARGVOUT
185 ENV INC SIG" is not allowed anywhere but in package "main::", for
186 technical reasons.
187
188 Unlike constants in some languages, these cannot be overridden on the
189 command line or via environment variables.
190
191 You can get into trouble if you use constants in a context which
192 automatically quotes barewords (as is true for any subroutine call).
193 For example, you can't say $hash{CONSTANT} because "CONSTANT" will be
194 interpreted as a string. Use $hash{CONSTANT()} or $hash{+CONSTANT} to
195 prevent the bareword quoting mechanism from kicking in. Similarly,
196 since the "=>" operator quotes a bareword immediately to its left, you
197 have to say "CONSTANT() => 'value'" (or simply use a comma in place of
198 the big arrow) instead of "CONSTANT => 'value'".
199
201 Readonly - Facility for creating read-only scalars, arrays, hashes.
202
203 Attribute::Constant - Make read-only variables via attribute
204
205 Scalar::Readonly - Perl extension to the "SvREADONLY" scalar flag
206
207 Hash::Util - A selection of general-utility hash subroutines (mostly to
208 lock/unlock keys and values)
209
211 Please report any bugs or feature requests via the perlbug(1) utility.
212
214 Tom Phoenix, <rootbeer@redcat.com>, with help from many other folks.
215
216 Multiple constant declarations at once added by Casey West,
217 <casey@geeknest.com>.
218
219 Documentation mostly rewritten by Ilmari Karonen, <perl@itz.pp.sci.fi>.
220
221 This program is maintained by the Perl 5 Porters. The CPAN
222 distribution is maintained by Sébastien Aperghis-Tramoni
223 <sebastien@aperghis.net>.
224
226 Copyright (C) 1997, 1999 Tom Phoenix
227
228 This module is free software; you can redistribute it or modify it
229 under the same terms as Perl itself.
230
231
232
233perl v5.34.0 2021-07-23 constant(3)