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