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