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