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