1constant(3pm) Perl Programmers Reference Guide constant(3pm)
2
3
4
6 constant - Perl pragma to declare constants
7
9 use constant PI => 4 * atan2(1, 1);
10 use constant DEBUG => 0;
11
12 print "Pi equals ", PI, "...\n" if DEBUG;
13
14 use constant {
15 SEC => 0,
16 MIN => 1,
17 HOUR => 2,
18 MDAY => 3,
19 MON => 4,
20 YEAR => 5,
21 WDAY => 6,
22 YDAY => 7,
23 ISDST => 8,
24 };
25
26 use constant WEEKDAYS => qw(
27 Sunday Monday Tuesday Wednesday Thursday Friday Saturday
28 );
29
30 print "Today is ", (WEEKDAYS)[ (localtime)[WDAY] ], ".\n";
31
33 This will declare a symbol to be a constant with the given value.
34
35 When you declare a constant such as "PI" using the method shown above,
36 each machine your script runs upon can have as many digits of accuracy
37 as it can use. Also, your program will be easier to read, more likely
38 to be maintained (and maintained correctly), and far less likely to
39 send a space probe to the wrong planet because nobody noticed the one
40 equation in which you wrote 3.14195.
41
42 When a constant is used in an expression, perl replaces it with its
43 value at compile time, and may then optimize the expression further.
44 In particular, any code in an "if (CONSTANT)" block will be optimized
45 away if the constant is false.
46
48 As with all "use" directives, defining a constant happens at compile
49 time. Thus, it's probably not correct to put a constant declaration
50 inside of a conditional statement (like "if ($foo) { use constant ...
51 }").
52
53 Constants defined using this module cannot be interpolated into strings
54 like variables. However, concatenation works just fine:
55
56 print "Pi equals PI...\n"; # WRONG: does not expand "PI"
57 print "Pi equals ".PI."...\n"; # right
58
59 Even though a reference may be declared as a constant, the reference
60 may point to data which may be changed, as this code shows.
61
62 use constant ARRAY => [ 1,2,3,4 ];
63 print ARRAY->[1];
64 ARRAY->[1] = " be changed";
65 print ARRAY->[1];
66
67 Dereferencing constant references incorrectly (such as using an array
68 subscript on a constant hash reference, or vice versa) will be trapped
69 at compile time.
70
71 Constants belong to the package they are defined in. To refer to a
72 constant defined in another package, specify the full package name, as
73 in "Some::Package::CONSTANT". Constants may be exported by modules,
74 and may also be called as either class or instance methods, that is, as
75 "Some::Package->CONSTANT" or as "$obj->CONSTANT" where $obj is an
76 instance of "Some::Package". Subclasses may define their own constants
77 to override those in their base class.
78
79 The use of all caps for constant names is merely a convention, although
80 it is recommended in order to make constants stand out and to help
81 avoid collisions with other barewords, keywords, and subroutine names.
82 Constant names must begin with a letter or underscore. Names beginning
83 with a double underscore are reserved. Some poor choices for names will
84 generate warnings, if warnings are enabled at compile time.
85
86 List constants
87
88 Constants may be lists of more (or less) than one value. A constant
89 with no values evaluates to "undef" in scalar context. Note that con‐
90 stants with more than one value do not return their last value in
91 scalar context as one might expect. They currently return the number
92 of values, but this may change in the future. Do not use constants
93 with multiple values in scalar context.
94
95 NOTE: This implies that the expression defining the value of a constant
96 is evaluated in list context. This may produce surprises:
97
98 use constant TIMESTAMP => localtime; # WRONG!
99 use constant TIMESTAMP => scalar localtime; # right
100
101 The first line above defines "TIMESTAMP" as a 9-element list, as
102 returned by localtime() in list context. To set it to the string
103 returned by localtime() in scalar context, an explicit "scalar" keyword
104 is required.
105
106 List constants are lists, not arrays. To index or slice them, they
107 must be placed in parentheses.
108
109 my @workdays = WEEKDAYS[1 .. 5]; # WRONG!
110 my @workdays = (WEEKDAYS)[1 .. 5]; # right
111
112 Defining multiple constants at once
113
114 Instead of writing multiple "use constant" statements, you may define
115 multiple constants in a single statement by giving, instead of the con‐
116 stant name, a reference to a hash where the keys are the names of the
117 constants to be defined. Obviously, all constants defined using this
118 method must have a single value.
119
120 use constant {
121 FOO => "A single value",
122 BAR => "This", "won't", "work!", # Error!
123 };
124
125 This is a fundamental limitation of the way hashes are constructed in
126 Perl. The error messages produced when this happens will often be
127 quite cryptic -- in the worst case there may be none at all, and you'll
128 only later find that something is broken.
129
130 When defining multiple constants, you cannot use the values of other
131 constants defined in the same declaration. This is because the calling
132 package doesn't know about any constant within that group until after
133 the "use" statement is finished.
134
135 use constant {
136 BITMASK => 0xAFBAEBA8,
137 NEGMASK => ~BITMASK, # Error!
138 };
139
140 Magic constants
141
142 Magical values and references can be made into constants at compile
143 time, allowing for way cool stuff like this. (These error numbers
144 aren't totally portable, alas.)
145
146 use constant E2BIG => ($! = 7);
147 print E2BIG, "\n"; # something like "Arg list too long"
148 print 0+E2BIG, "\n"; # "7"
149
150 You can't produce a tied constant by giving a tied scalar as the value.
151 References to tied variables, however, can be used as constants without
152 any problems.
153
155 In the current implementation, scalar constants are actually inlinable
156 subroutines. As of version 5.004 of Perl, the appropriate scalar con‐
157 stant is inserted directly in place of some subroutine calls, thereby
158 saving the overhead of a subroutine call. See "Constant Functions" in
159 perlsub for details about how and when this happens.
160
161 In the rare case in which you need to discover at run time whether a
162 particular constant has been declared via this module, you may use this
163 function to examine the hash %constant::declared. If the given constant
164 name does not include a package name, the current package is used.
165
166 sub declared ($) {
167 use constant 1.01; # don't omit this!
168 my $name = shift;
169 $name =~ s/^::/main::/;
170 my $pkg = caller;
171 my $full_name = $name =~ /::/ ? $name : "${pkg}::$name";
172 $constant::declared{$full_name};
173 }
174
176 In the current version of Perl, list constants are not inlined and some
177 symbols may be redefined without generating a warning.
178
179 It is not possible to have a subroutine or a keyword with the same name
180 as a constant in the same package. This is probably a Good Thing.
181
182 A constant with a name in the list "STDIN STDOUT STDERR ARGV ARGVOUT
183 ENV INC SIG" is not allowed anywhere but in package "main::", for tech‐
184 nical reasons.
185
186 Unlike constants in some languages, these cannot be overridden on the
187 command line or via environment variables.
188
189 You can get into trouble if you use constants in a context which auto‐
190 matically quotes barewords (as is true for any subroutine call). For
191 example, you can't say $hash{CONSTANT} because "CONSTANT" will be
192 interpreted as a string. Use $hash{CONSTANT()} or $hash{+CONSTANT} to
193 prevent the bareword quoting mechanism from kicking in. Similarly,
194 since the "=>" operator quotes a bareword immediately to its left, you
195 have to say "CONSTANT() => 'value'" (or simply use a comma in place of
196 the big arrow) instead of "CONSTANT => 'value'".
197
199 Tom Phoenix, <rootbeer@redcat.com>, with help from many other folks.
200
201 Multiple constant declarations at once added by Casey West,
202 <casey@geeknest.com>.
203
204 Documentation mostly rewritten by Ilmari Karonen, <perl@itz.pp.sci.fi>.
205
207 Copyright (C) 1997, 1999 Tom Phoenix
208
209 This module is free software; you can redistribute it or modify it
210 under the same terms as Perl itself.
211
212
213
214perl v5.8.8 2001-09-21 constant(3pm)