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