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