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 pragma allows you to declare constants at compile-time.
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 Constants may be lists of more (or less) than one value. A constant
88 with no values evaluates to "undef" in scalar context. Note that
89 constants with more than one value do not return their last value in
90 scalar context as one might expect. They currently return the number
91 of values, but this may change in the future. Do not use constants
92 with multiple values in scalar context.
93
94 NOTE: This implies that the expression defining the value of a constant
95 is evaluated in list context. This may produce surprises:
96
97 use constant TIMESTAMP => localtime; # WRONG!
98 use constant TIMESTAMP => scalar localtime; # right
99
100 The first line above defines "TIMESTAMP" as a 9-element list, as
101 returned by "localtime()" in list context. To set it to the string
102 returned by "localtime()" in scalar context, an explicit "scalar"
103 keyword is required.
104
105 List constants are lists, not arrays. To index or slice them, they
106 must be placed in parentheses.
107
108 my @workdays = WEEKDAYS[1 .. 5]; # WRONG!
109 my @workdays = (WEEKDAYS)[1 .. 5]; # right
110
111 Defining multiple constants at once
112 Instead of writing multiple "use constant" statements, you may define
113 multiple constants in a single statement by giving, instead of the
114 constant name, a reference to a hash where the keys are the names of
115 the constants to be defined. Obviously, all constants defined using
116 this method must have a single value.
117
118 use constant {
119 FOO => "A single value",
120 BAR => "This", "won't", "work!", # Error!
121 };
122
123 This is a fundamental limitation of the way hashes are constructed in
124 Perl. The error messages produced when this happens will often be
125 quite cryptic -- in the worst case there may be none at all, and you'll
126 only later find that something is broken.
127
128 When defining multiple constants, you cannot use the values of other
129 constants defined in the same declaration. This is because the calling
130 package doesn't know about any constant within that group until after
131 the "use" statement is finished.
132
133 use constant {
134 BITMASK => 0xAFBAEBA8,
135 NEGMASK => ~BITMASK, # Error!
136 };
137
138 Magic constants
139 Magical values and references can be made into constants at compile
140 time, allowing for way cool stuff like this. (These error numbers
141 aren't totally portable, alas.)
142
143 use constant E2BIG => ($! = 7);
144 print E2BIG, "\n"; # something like "Arg list too long"
145 print 0+E2BIG, "\n"; # "7"
146
147 You can't produce a tied constant by giving a tied scalar as the value.
148 References to tied variables, however, can be used as constants without
149 any problems.
150
152 In the current implementation, scalar constants are actually inlinable
153 subroutines. As of version 5.004 of Perl, the appropriate scalar
154 constant is inserted directly in place of some subroutine calls,
155 thereby saving the overhead of a subroutine call. See "Constant
156 Functions" in perlsub for details about how and when this happens.
157
158 In the rare case in which you need to discover at run time whether a
159 particular constant has been declared via this module, you may use this
160 function to examine the hash %constant::declared. If the given constant
161 name does not include a package name, the current package is used.
162
163 sub declared ($) {
164 use constant 1.01; # don't omit this!
165 my $name = shift;
166 $name =~ s/^::/main::/;
167 my $pkg = caller;
168 my $full_name = $name =~ /::/ ? $name : "${pkg}::$name";
169 $constant::declared{$full_name};
170 }
171
173 In the current version of Perl, list constants are not inlined and some
174 symbols may be redefined without generating a warning.
175
176 It is not possible to have a subroutine or a keyword with the same name
177 as a constant in the same package. This is probably a Good Thing.
178
179 A constant with a name in the list "STDIN STDOUT STDERR ARGV ARGVOUT
180 ENV INC SIG" is not allowed anywhere but in package "main::", for
181 technical reasons.
182
183 Unlike constants in some languages, these cannot be overridden on the
184 command line or via environment variables.
185
186 You can get into trouble if you use constants in a context which
187 automatically quotes barewords (as is true for any subroutine call).
188 For example, you can't say $hash{CONSTANT} because "CONSTANT" will be
189 interpreted as a string. Use $hash{CONSTANT()} or $hash{+CONSTANT} to
190 prevent the bareword quoting mechanism from kicking in. Similarly,
191 since the "=>" operator quotes a bareword immediately to its left, you
192 have to say "CONSTANT() => 'value'" (or simply use a comma in place of
193 the big arrow) instead of "CONSTANT => 'value'".
194
196 Readonly - Facility for creating read-only scalars, arrays, hashes.
197
198 Const - Facility for creating read-only variables. Similar to
199 "Readonly", but uses "SvREADONLY" instead of "tie".
200
201 Attribute::Constant - Make read-only variables via attribute
202
203 Scalar::Readonly - Perl extension to the "SvREADONLY" scalar flag
204
205 Hash::Util - A selection of general-utility hash subroutines (mostly to
206 lock/unlock keys and values)
207
209 Please report any bugs or feature requests via the perlbug(1) utility.
210
212 Tom Phoenix, <rootbeer@redcat.com>, with help from many other folks.
213
214 Multiple constant declarations at once added by Casey West,
215 <casey@geeknest.com>.
216
217 Documentation mostly rewritten by Ilmari Karonen, <perl@itz.pp.sci.fi>.
218
219 This program is maintained by the Perl 5 Porters. The CPAN
220 distribution is maintained by Sebastien Aperghis-Tramoni
221 <sebastien@aperghis.net>.
222
224 Copyright (C) 1997, 1999 Tom Phoenix
225
226 This module is free software; you can redistribute it or modify it
227 under the same terms as Perl itself.
228
229
230
231perl v5.12.4 2011-06-07 constant(3pm)