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