Commit | Line | Data |
---|---|---|
54310121 | 1 | package constant; |
eb10a876 | 2 | use 5.008; |
83763826 | 3 | use strict; |
d3a7d8c7 | 4 | use warnings::register; |
17f410f9 | 5 | |
6515510f | 6 | use vars qw($VERSION %declared); |
f2952d39 | 7 | $VERSION = '1.28'; |
83763826 GS |
8 | |
9 | #======================================================================= | |
10 | ||
83763826 | 11 | # Some names are evil choices. |
83b99c4f NC |
12 | my %keywords = map +($_, 1), qw{ BEGIN INIT CHECK END DESTROY AUTOLOAD }; |
13 | $keywords{UNITCHECK}++ if $] > 5.009; | |
83763826 GS |
14 | |
15 | my %forced_into_main = map +($_, 1), | |
16 | qw{ STDIN STDOUT STDERR ARGV ARGVOUT ENV INC SIG }; | |
17 | ||
18 | my %forbidden = (%keywords, %forced_into_main); | |
19 | ||
eb10a876 JK |
20 | my $normal_constant_name = qr/^_?[^\W_0-9]\w*\z/; |
21 | my $tolerable = qr/^[A-Za-z_]\w*\z/; | |
22 | my $boolean = qr/^[01]?\z/; | |
672c0ce9 | 23 | |
c5764f70 NC |
24 | BEGIN { |
25 | # We'd like to do use constant _CAN_PCS => $] > 5.009002 | |
26 | # but that's a bit tricky before we load the constant module :-) | |
27 | # By doing this, we save 1 run time check for *every* call to import. | |
c5764f70 | 28 | my $const = $] > 5.009002; |
2b7e302a | 29 | my $downgrade = $] < 5.015004; # && $] >= 5.008 |
15635cbf | 30 | my $constarray = $] > 5.019001; |
94d5c174 FC |
31 | if ($const) { |
32 | Internals::SvREADONLY($const, 1); | |
33 | Internals::SvREADONLY($downgrade, 1); | |
34 | $constant::{_CAN_PCS} = \$const; | |
35 | $constant::{_DOWNGRADE} = \$downgrade; | |
15635cbf | 36 | $constant::{_CAN_PCS_FOR_ARRAY} = \$constarray; |
94d5c174 FC |
37 | } |
38 | else { | |
39 | no strict 'refs'; | |
40 | *{"_CAN_PCS"} = sub () {$const}; | |
41 | *{"_DOWNGRADE"} = sub () { $downgrade }; | |
15635cbf | 42 | *{"_CAN_PCS_FOR_ARRAY"} = sub () { $constarray }; |
94d5c174 | 43 | } |
c5764f70 NC |
44 | } |
45 | ||
83763826 GS |
46 | #======================================================================= |
47 | # import() - import symbols into user's namespace | |
48 | # | |
49 | # What we actually do is define a function in the caller's namespace | |
50 | # which returns the value. The function we create will normally | |
51 | # be inlined as a constant, thereby avoiding further sub calling | |
52 | # overhead. | |
53 | #======================================================================= | |
54 | sub import { | |
55 | my $class = shift; | |
56 | return unless @_; # Ignore 'use constant;' | |
b35226bb | 57 | my $constants; |
3cb88d13 | 58 | my $multiple = ref $_[0]; |
39a108ce | 59 | my $pkg = caller; |
f7fd2659 | 60 | my $flush_mro; |
e040ff70 NC |
61 | my $symtab; |
62 | ||
c5764f70 | 63 | if (_CAN_PCS) { |
e040ff70 NC |
64 | no strict 'refs'; |
65 | $symtab = \%{$pkg . '::'}; | |
66 | }; | |
3cb88d13 CT |
67 | |
68 | if ( $multiple ) { | |
69 | if (ref $_[0] ne 'HASH') { | |
70 | require Carp; | |
71 | Carp::croak("Invalid reference type '".ref(shift)."' not 'HASH'"); | |
72 | } | |
b35226bb | 73 | $constants = shift; |
3cb88d13 | 74 | } else { |
15dc519f | 75 | unless (defined $_[0]) { |
3cb88d13 CT |
76 | require Carp; |
77 | Carp::croak("Can't use undef as constant name"); | |
78 | } | |
15dc519f Z |
79 | $constants->{+shift} = undef; |
80 | } | |
3cb88d13 | 81 | |
15dc519f | 82 | foreach my $name ( keys %$constants ) { |
3cb88d13 | 83 | # Normal constant name |
672c0ce9 | 84 | if ($name =~ $normal_constant_name and !$forbidden{$name}) { |
3cb88d13 CT |
85 | # Everything is okay |
86 | ||
87 | # Name forced into main, but we're not in main. Fatal. | |
88 | } elsif ($forced_into_main{$name} and $pkg ne 'main') { | |
89 | require Carp; | |
90 | Carp::croak("Constant name '$name' is forced into main::"); | |
91 | ||
92 | # Starts with double underscore. Fatal. | |
93 | } elsif ($name =~ /^__/) { | |
94 | require Carp; | |
95 | Carp::croak("Constant name '$name' begins with '__'"); | |
96 | ||
97 | # Maybe the name is tolerable | |
672c0ce9 | 98 | } elsif ($name =~ $tolerable) { |
3cb88d13 CT |
99 | # Then we'll warn only if you've asked for warnings |
100 | if (warnings::enabled()) { | |
101 | if ($keywords{$name}) { | |
102 | warnings::warn("Constant name '$name' is a Perl keyword"); | |
103 | } elsif ($forced_into_main{$name}) { | |
104 | warnings::warn("Constant name '$name' is " . | |
105 | "forced into package main::"); | |
3cb88d13 CT |
106 | } |
107 | } | |
108 | ||
109 | # Looks like a boolean | |
110 | # use constant FRED == fred; | |
672c0ce9 | 111 | } elsif ($name =~ $boolean) { |
3cb88d13 CT |
112 | require Carp; |
113 | if (@_) { | |
114 | Carp::croak("Constant name '$name' is invalid"); | |
83763826 | 115 | } else { |
3cb88d13 | 116 | Carp::croak("Constant name looks like boolean value"); |
83763826 | 117 | } |
83763826 | 118 | |
83763826 | 119 | } else { |
3cb88d13 CT |
120 | # Must have bad characters |
121 | require Carp; | |
122 | Carp::croak("Constant name '$name' has invalid characters"); | |
83763826 GS |
123 | } |
124 | ||
3cb88d13 CT |
125 | { |
126 | no strict 'refs'; | |
127 | my $full_name = "${pkg}::$name"; | |
128 | $declared{$full_name}++; | |
e040ff70 NC |
129 | if ($multiple || @_ == 1) { |
130 | my $scalar = $multiple ? $constants->{$name} : $_[0]; | |
d12b49d6 | 131 | |
2d1c5561 | 132 | if (_DOWNGRADE) { # for 5.8 to 5.14 |
bd8cb552 FC |
133 | # Work around perl bug #31991: Sub names (actually glob |
134 | # names in general) ignore the UTF8 flag. So we have to | |
135 | # turn it off to get the "right" symbol table entry. | |
136 | utf8::is_utf8 $name and utf8::encode $name; | |
137 | } | |
d12b49d6 | 138 | |
a8ae8fee NC |
139 | # The constant serves to optimise this entire block out on |
140 | # 5.8 and earlier. | |
94d5c174 FC |
141 | if (_CAN_PCS) { |
142 | # Use a reference as a proxy for a constant subroutine. | |
143 | # If this is not a glob yet, it saves space. If it is | |
144 | # a glob, we must still create it this way to get the | |
145 | # right internal flags set, as constants are distinct | |
146 | # from subroutines created with sub(){...}. | |
e040ff70 NC |
147 | # The check in Perl_ck_rvconst knows that inlinable |
148 | # constants from cv_const_sv are read only. So we have to: | |
149 | Internals::SvREADONLY($scalar, 1); | |
94d5c174 FC |
150 | if ($symtab && !exists $symtab->{$name}) { |
151 | $symtab->{$name} = \$scalar; | |
152 | ++$flush_mro; | |
153 | } | |
154 | else { | |
155 | local $constant::{_dummy} = \$scalar; | |
156 | *$full_name = \&{"_dummy"}; | |
157 | } | |
3cb88d13 | 158 | } else { |
e040ff70 | 159 | *$full_name = sub () { $scalar }; |
3cb88d13 | 160 | } |
e040ff70 NC |
161 | } elsif (@_) { |
162 | my @list = @_; | |
15635cbf FC |
163 | if (_CAN_PCS_FOR_ARRAY) { |
164 | Internals::SvREADONLY(@list, 1); | |
165 | Internals::SvREADONLY($list[$_], 1) for 0..$#list; | |
166 | if ($symtab && !exists $symtab->{$name}) { | |
167 | $symtab->{$name} = \@list; | |
168 | $flush_mro++; | |
169 | } | |
170 | else { | |
171 | local $constant::{_dummy} = \@list; | |
172 | *$full_name = \&{"_dummy"}; | |
173 | } | |
174 | } | |
175 | else { *$full_name = sub () { @list }; } | |
e040ff70 NC |
176 | } else { |
177 | *$full_name = sub () { }; | |
3cb88d13 | 178 | } |
83763826 GS |
179 | } |
180 | } | |
f7fd2659 | 181 | # Flush the cache exactly once if we make any direct symbol table changes. |
a8ae8fee | 182 | mro::method_changed_in($pkg) if _CAN_PCS && $flush_mro; |
83763826 GS |
183 | } |
184 | ||
185 | 1; | |
186 | ||
187 | __END__ | |
54310121 | 188 | |
189 | =head1 NAME | |
190 | ||
191 | constant - Perl pragma to declare constants | |
192 | ||
193 | =head1 SYNOPSIS | |
194 | ||
a747501d AMS |
195 | use constant PI => 4 * atan2(1, 1); |
196 | use constant DEBUG => 0; | |
197 | ||
198 | print "Pi equals ", PI, "...\n" if DEBUG; | |
199 | ||
3cb88d13 | 200 | use constant { |
a747501d AMS |
201 | SEC => 0, |
202 | MIN => 1, | |
203 | HOUR => 2, | |
204 | MDAY => 3, | |
205 | MON => 4, | |
206 | YEAR => 5, | |
207 | WDAY => 6, | |
208 | YDAY => 7, | |
209 | ISDST => 8, | |
3cb88d13 CT |
210 | }; |
211 | ||
a747501d AMS |
212 | use constant WEEKDAYS => qw( |
213 | Sunday Monday Tuesday Wednesday Thursday Friday Saturday | |
214 | ); | |
215 | ||
216 | print "Today is ", (WEEKDAYS)[ (localtime)[WDAY] ], ".\n"; | |
217 | ||
54310121 | 218 | =head1 DESCRIPTION |
219 | ||
6515510f | 220 | This pragma allows you to declare constants at compile-time. |
54310121 | 221 | |
222 | When you declare a constant such as C<PI> using the method shown | |
223 | above, each machine your script runs upon can have as many digits | |
224 | of accuracy as it can use. Also, your program will be easier to | |
225 | read, more likely to be maintained (and maintained correctly), and | |
226 | far less likely to send a space probe to the wrong planet because | |
227 | nobody noticed the one equation in which you wrote C<3.14195>. | |
228 | ||
d3383c75 | 229 | When a constant is used in an expression, Perl replaces it with its |
a747501d AMS |
230 | value at compile time, and may then optimize the expression further. |
231 | In particular, any code in an C<if (CONSTANT)> block will be optimized | |
232 | away if the constant is false. | |
233 | ||
54310121 | 234 | =head1 NOTES |
235 | ||
a747501d AMS |
236 | As with all C<use> directives, defining a constant happens at |
237 | compile time. Thus, it's probably not correct to put a constant | |
238 | declaration inside of a conditional statement (like C<if ($foo) | |
239 | { use constant ... }>). | |
54310121 | 240 | |
a747501d AMS |
241 | Constants defined using this module cannot be interpolated into |
242 | strings like variables. However, concatenation works just fine: | |
54310121 | 243 | |
a747501d AMS |
244 | print "Pi equals PI...\n"; # WRONG: does not expand "PI" |
245 | print "Pi equals ".PI."...\n"; # right | |
54310121 | 246 | |
a747501d AMS |
247 | Even though a reference may be declared as a constant, the reference may |
248 | point to data which may be changed, as this code shows. | |
249 | ||
250 | use constant ARRAY => [ 1,2,3,4 ]; | |
251 | print ARRAY->[1]; | |
252 | ARRAY->[1] = " be changed"; | |
253 | print ARRAY->[1]; | |
254 | ||
255 | Dereferencing constant references incorrectly (such as using an array | |
256 | subscript on a constant hash reference, or vice versa) will be trapped at | |
257 | compile time. | |
54310121 | 258 | |
a747501d AMS |
259 | Constants belong to the package they are defined in. To refer to a |
260 | constant defined in another package, specify the full package name, as | |
261 | in C<Some::Package::CONSTANT>. Constants may be exported by modules, | |
262 | and may also be called as either class or instance methods, that is, | |
263 | as C<< Some::Package->CONSTANT >> or as C<< $obj->CONSTANT >> where | |
264 | C<$obj> is an instance of C<Some::Package>. Subclasses may define | |
265 | their own constants to override those in their base class. | |
54310121 | 266 | |
267 | The use of all caps for constant names is merely a convention, | |
268 | although it is recommended in order to make constants stand out | |
269 | and to help avoid collisions with other barewords, keywords, and | |
83763826 GS |
270 | subroutine names. Constant names must begin with a letter or |
271 | underscore. Names beginning with a double underscore are reserved. Some | |
272 | poor choices for names will generate warnings, if warnings are enabled at | |
273 | compile time. | |
54310121 | 274 | |
a747501d | 275 | =head2 List constants |
54310121 | 276 | |
a747501d AMS |
277 | Constants may be lists of more (or less) than one value. A constant |
278 | with no values evaluates to C<undef> in scalar context. Note that | |
279 | constants with more than one value do I<not> return their last value in | |
280 | scalar context as one might expect. They currently return the number | |
281 | of values, but B<this may change in the future>. Do not use constants | |
282 | with multiple values in scalar context. | |
3cb88d13 | 283 | |
a747501d AMS |
284 | B<NOTE:> This implies that the expression defining the value of a |
285 | constant is evaluated in list context. This may produce surprises: | |
54310121 | 286 | |
a747501d AMS |
287 | use constant TIMESTAMP => localtime; # WRONG! |
288 | use constant TIMESTAMP => scalar localtime; # right | |
54310121 | 289 | |
a747501d | 290 | The first line above defines C<TIMESTAMP> as a 9-element list, as |
6515510f AT |
291 | returned by C<localtime()> in list context. To set it to the string |
292 | returned by C<localtime()> in scalar context, an explicit C<scalar> | |
a747501d | 293 | keyword is required. |
54310121 | 294 | |
a747501d AMS |
295 | List constants are lists, not arrays. To index or slice them, they |
296 | must be placed in parentheses. | |
54310121 | 297 | |
a747501d AMS |
298 | my @workdays = WEEKDAYS[1 .. 5]; # WRONG! |
299 | my @workdays = (WEEKDAYS)[1 .. 5]; # right | |
b0d6893f | 300 | |
a747501d | 301 | =head2 Defining multiple constants at once |
b0d6893f | 302 | |
a747501d AMS |
303 | Instead of writing multiple C<use constant> statements, you may define |
304 | multiple constants in a single statement by giving, instead of the | |
305 | constant name, a reference to a hash where the keys are the names of | |
306 | the constants to be defined. Obviously, all constants defined using | |
307 | this method must have a single value. | |
308 | ||
309 | use constant { | |
310 | FOO => "A single value", | |
311 | BAR => "This", "won't", "work!", # Error! | |
312 | }; | |
313 | ||
314 | This is a fundamental limitation of the way hashes are constructed in | |
315 | Perl. The error messages produced when this happens will often be | |
316 | quite cryptic -- in the worst case there may be none at all, and | |
317 | you'll only later find that something is broken. | |
318 | ||
319 | When defining multiple constants, you cannot use the values of other | |
320 | constants defined in the same declaration. This is because the | |
321 | calling package doesn't know about any constant within that group | |
322 | until I<after> the C<use> statement is finished. | |
323 | ||
324 | use constant { | |
325 | BITMASK => 0xAFBAEBA8, | |
326 | NEGMASK => ~BITMASK, # Error! | |
327 | }; | |
328 | ||
329 | =head2 Magic constants | |
b0d6893f IK |
330 | |
331 | Magical values and references can be made into constants at compile | |
332 | time, allowing for way cool stuff like this. (These error numbers | |
333 | aren't totally portable, alas.) | |
54310121 | 334 | |
335 | use constant E2BIG => ($! = 7); | |
a747501d AMS |
336 | print E2BIG, "\n"; # something like "Arg list too long" |
337 | print 0+E2BIG, "\n"; # "7" | |
54310121 | 338 | |
b0d6893f IK |
339 | You can't produce a tied constant by giving a tied scalar as the |
340 | value. References to tied variables, however, can be used as | |
341 | constants without any problems. | |
342 | ||
a747501d | 343 | =head1 TECHNICAL NOTES |
b0d6893f | 344 | |
a747501d AMS |
345 | In the current implementation, scalar constants are actually |
346 | inlinable subroutines. As of version 5.004 of Perl, the appropriate | |
347 | scalar constant is inserted directly in place of some subroutine | |
348 | calls, thereby saving the overhead of a subroutine call. See | |
349 | L<perlsub/"Constant Functions"> for details about how and when this | |
350 | happens. | |
3cb88d13 | 351 | |
83763826 GS |
352 | In the rare case in which you need to discover at run time whether a |
353 | particular constant has been declared via this module, you may use | |
354 | this function to examine the hash C<%constant::declared>. If the given | |
355 | constant name does not include a package name, the current package is | |
356 | used. | |
357 | ||
358 | sub declared ($) { | |
a747501d AMS |
359 | use constant 1.01; # don't omit this! |
360 | my $name = shift; | |
361 | $name =~ s/^::/main::/; | |
362 | my $pkg = caller; | |
363 | my $full_name = $name =~ /::/ ? $name : "${pkg}::$name"; | |
364 | $constant::declared{$full_name}; | |
83763826 | 365 | } |
779c5bc9 | 366 | |
6515510f | 367 | =head1 CAVEATS |
54310121 | 368 | |
c5a24412 | 369 | List constants were not inlined unless you are using Perl v5.20 or higher. |
54310121 | 370 | |
a747501d | 371 | It is not possible to have a subroutine or a keyword with the same |
83763826 GS |
372 | name as a constant in the same package. This is probably a Good Thing. |
373 | ||
374 | A constant with a name in the list C<STDIN STDOUT STDERR ARGV ARGVOUT | |
375 | ENV INC SIG> is not allowed anywhere but in package C<main::>, for | |
376 | technical reasons. | |
377 | ||
54310121 | 378 | Unlike constants in some languages, these cannot be overridden |
379 | on the command line or via environment variables. | |
380 | ||
a3cb178b GS |
381 | You can get into trouble if you use constants in a context which |
382 | automatically quotes barewords (as is true for any subroutine call). | |
383 | For example, you can't say C<$hash{CONSTANT}> because C<CONSTANT> will | |
384 | be interpreted as a string. Use C<$hash{CONSTANT()}> or | |
385 | C<$hash{+CONSTANT}> to prevent the bareword quoting mechanism from | |
a747501d AMS |
386 | kicking in. Similarly, since the C<< => >> operator quotes a bareword |
387 | immediately to its left, you have to say C<< CONSTANT() => 'value' >> | |
83763826 | 388 | (or simply use a comma in place of the big arrow) instead of |
a747501d | 389 | C<< CONSTANT => 'value' >>. |
a3cb178b | 390 | |
d3383c75 AT |
391 | =head1 SEE ALSO |
392 | ||
393 | L<Readonly> - Facility for creating read-only scalars, arrays, hashes. | |
394 | ||
d3383c75 AT |
395 | L<Attribute::Constant> - Make read-only variables via attribute |
396 | ||
397 | L<Scalar::Readonly> - Perl extension to the C<SvREADONLY> scalar flag | |
398 | ||
399 | L<Hash::Util> - A selection of general-utility hash subroutines (mostly | |
400 | to lock/unlock keys and values) | |
401 | ||
6515510f AT |
402 | =head1 BUGS |
403 | ||
404 | Please report any bugs or feature requests via the perlbug(1) utility. | |
405 | ||
406 | =head1 AUTHORS | |
54310121 | 407 | |
83763826 | 408 | Tom Phoenix, E<lt>F<rootbeer@redcat.com>E<gt>, with help from |
54310121 | 409 | many other folks. |
410 | ||
e1e60e72 CW |
411 | Multiple constant declarations at once added by Casey West, |
412 | E<lt>F<casey@geeknest.com>E<gt>. | |
3cb88d13 | 413 | |
a747501d | 414 | Documentation mostly rewritten by Ilmari Karonen, |
b0d6893f IK |
415 | E<lt>F<perl@itz.pp.sci.fi>E<gt>. |
416 | ||
6515510f AT |
417 | This program is maintained by the Perl 5 Porters. |
418 | The CPAN distribution is maintained by SE<eacute>bastien Aperghis-Tramoni | |
419 | E<lt>F<sebastien@aperghis.net>E<gt>. | |
420 | ||
d3383c75 | 421 | =head1 COPYRIGHT & LICENSE |
54310121 | 422 | |
83763826 | 423 | Copyright (C) 1997, 1999 Tom Phoenix |
54310121 | 424 | |
425 | This module is free software; you can redistribute it or modify it | |
426 | under the same terms as Perl itself. | |
427 | ||
428 | =cut |