This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Continue what #4494 started; introduce uid and gid formats.
[perl5.git] / lib / constant.pm
CommitLineData
54310121 1package constant;
2
3$VERSION = '1.00';
4
5=head1 NAME
6
7constant - Perl pragma to declare constants
8
9=head1 SYNOPSIS
10
11 use constant BUFFER_SIZE => 4096;
12 use constant ONE_YEAR => 365.2425 * 24 * 60 * 60;
13 use constant PI => 4 * atan2 1, 1;
14 use constant DEBUGGING => 0;
15 use constant ORACLE => 'oracle@cs.indiana.edu';
16 use constant USERNAME => scalar getpwuid($<);
17 use constant USERINFO => getpwuid($<);
18
19 sub deg2rad { PI * $_[0] / 180 }
20
21 print "This line does nothing" unless DEBUGGING;
22
779c5bc9
GS
23 # references can be declared constant
24 use constant CHASH => { foo => 42 };
25 use constant CARRAY => [ 1,2,3,4 ];
26 use constant CPSEUDOHASH => [ { foo => 1}, 42 ];
27 use constant CCODE => sub { "bite $_[0]\n" };
28
29 print CHASH->{foo};
30 print CARRAY->[$i];
31 print CPSEUDOHASH->{foo};
32 print CCODE->("me");
33 print CHASH->[10]; # compile-time error
34
54310121 35=head1 DESCRIPTION
36
37This will declare a symbol to be a constant with the given scalar
38or list value.
39
40When you declare a constant such as C<PI> using the method shown
41above, each machine your script runs upon can have as many digits
42of accuracy as it can use. Also, your program will be easier to
43read, more likely to be maintained (and maintained correctly), and
44far less likely to send a space probe to the wrong planet because
45nobody noticed the one equation in which you wrote C<3.14195>.
46
47=head1 NOTES
48
49The value or values are evaluated in a list context. You may override
50this with C<scalar> as shown above.
51
52These constants do not directly interpolate into double-quotish
53strings, although you may do so indirectly. (See L<perlref> for
54details about how this works.)
55
56 print "The value of PI is @{[ PI ]}.\n";
57
58List constants are returned as lists, not as arrays.
59
60 $homedir = USERINFO[7]; # WRONG
61 $homedir = (USERINFO)[7]; # Right
62
63The use of all caps for constant names is merely a convention,
64although it is recommended in order to make constants stand out
65and to help avoid collisions with other barewords, keywords, and
66subroutine names. Constant names must begin with a letter.
67
68Constant symbols are package scoped (rather than block scoped, as
69C<use strict> is). That is, you can refer to a constant from package
70Other as C<Other::CONST>.
71
72As with all C<use> directives, defining a constant happens at
73compile time. Thus, it's probably not correct to put a constant
74declaration inside of a conditional statement (like C<if ($foo)
75{ use constant ... }>).
76
77Omitting the value for a symbol gives it the value of C<undef> in
78a scalar context or the empty list, C<()>, in a list context. This
79isn't so nice as it may sound, though, because in this case you
80must either quote the symbol name, or use a big arrow, (C<=E<gt>>),
81with nothing to point to. It is probably best to declare these
82explicitly.
83
84 use constant UNICORNS => ();
85 use constant LOGFILE => undef;
86
87The result from evaluating a list constant in a scalar context is
88not documented, and is B<not> guaranteed to be any particular value
89in the future. In particular, you should not rely upon it being
90the number of elements in the list, especially since it is not
91B<necessarily> that value in the current implementation.
92
93Magical values, tied values, and references can be made into
94constants at compile time, allowing for way cool stuff like this.
7e5dee47 95(These error numbers aren't totally portable, alas.)
54310121 96
97 use constant E2BIG => ($! = 7);
98 print E2BIG, "\n"; # something like "Arg list too long"
99 print 0+E2BIG, "\n"; # "7"
100
779c5bc9
GS
101Errors in dereferencing constant references are trapped at compile-time.
102
54310121 103=head1 TECHNICAL NOTE
104
105In the current implementation, scalar constants are actually
106inlinable subroutines. As of version 5.004 of Perl, the appropriate
107scalar constant is inserted directly in place of some subroutine
108calls, thereby saving the overhead of a subroutine call. See
109L<perlsub/"Constant Functions"> for details about how and when this
110happens.
111
112=head1 BUGS
113
114In the current version of Perl, list constants are not inlined
115and some symbols may be redefined without generating a warning.
116
117It is not possible to have a subroutine or keyword with the same
118name as a constant. This is probably a Good Thing.
119
120Unlike constants in some languages, these cannot be overridden
121on the command line or via environment variables.
122
a3cb178b
GS
123You can get into trouble if you use constants in a context which
124automatically quotes barewords (as is true for any subroutine call).
125For example, you can't say C<$hash{CONSTANT}> because C<CONSTANT> will
126be interpreted as a string. Use C<$hash{CONSTANT()}> or
127C<$hash{+CONSTANT}> to prevent the bareword quoting mechanism from
128kicking in. Similarly, since the C<=E<gt>> operator quotes a bareword
129immediately to its left you have to say C<CONSTANT() =E<gt> 'value'>
130instead of C<CONSTANT =E<gt> 'value'>.
131
54310121 132=head1 AUTHOR
133
134Tom Phoenix, E<lt>F<rootbeer@teleport.com>E<gt>, with help from
135many other folks.
136
137=head1 COPYRIGHT
138
139Copyright (C) 1997, Tom Phoenix
140
141This module is free software; you can redistribute it or modify it
142under the same terms as Perl itself.
143
144=cut
145
146use strict;
147use Carp;
148use vars qw($VERSION);
149
150#=======================================================================
151
152# Some of this stuff didn't work in version 5.003, alas.
7e5dee47 153require 5.003_96;
54310121 154
155#=======================================================================
156# import() - import symbols into user's namespace
157#
158# What we actually do is define a function in the caller's namespace
159# which returns the value. The function we create will normally
160# be inlined as a constant, thereby avoiding further sub calling
161# overhead.
162#=======================================================================
163sub import {
164 my $class = shift;
165 my $name = shift or return; # Ignore 'use constant;'
166 croak qq{Can't define "$name" as constant} .
167 qq{ (name contains invalid characters or is empty)}
168 unless $name =~ /^[^\W_0-9]\w*$/;
169
170 my $pkg = caller;
171 {
172 no strict 'refs';
173 if (@_ == 1) {
174 my $scalar = $_[0];
175 *{"${pkg}::$name"} = sub () { $scalar };
176 } elsif (@_) {
177 my @list = @_;
178 *{"${pkg}::$name"} = sub () { @list };
179 } else {
180 *{"${pkg}::$name"} = sub () { };
181 }
182 }
183
184}
185
1861;