1Readonly(3pm) User Contributed Perl Documentation Readonly(3pm)
2
3
4
6 Readonly - Facility for creating read-only scalars, arrays, hashes
7
9 use Readonly;
10
11 # Deep Read-only scalar
12 Readonly::Scalar $sca => $initial_value;
13 Readonly::Scalar my $sca => $initial_value;
14
15 # Deep Read-only array
16 Readonly::Array @arr => @values;
17 Readonly::Array my @arr => @values;
18
19 # Deep Read-only hash
20 Readonly::Hash %has => (key => value, key => value, ...);
21 Readonly::Hash my %has => (key => value, key => value, ...);
22 # or:
23 Readonly::Hash %has => {key => value, key => value, ...};
24
25 # You can use the read-only variables like any regular variables:
26 print $sca;
27 $something = $sca + $arr[2];
28 next if $has{$some_key};
29
30 # But if you try to modify a value, your program will die:
31 $sca = 7;
32 push @arr, 'seven';
33 delete $has{key};
34 # The error message is "Modification of a read-only value attempted"
35
36 # Alternate form (Perl 5.8 and later)
37 Readonly $sca => $initial_value;
38 Readonly my $sca => $initial_value;
39 Readonly @arr => @values;
40 Readonly my @arr => @values;
41 Readonly %has => (key => value, key => value, ...);
42 Readonly my %has => (key => value, key => value, ...);
43 Readonly my $sca; # Implicit undef, readonly value
44
45 # Alternate form (for Perls earlier than v5.8)
46 Readonly \$sca => $initial_value;
47 Readonly \my $sca => $initial_value;
48 Readonly \@arr => @values;
49 Readonly \my @arr => @values;
50 Readonly \%has => (key => value, key => value, ...);
51 Readonly \my %has => (key => value, key => value, ...);
52
54 This is a facility for creating non-modifiable variables. This is
55 useful for configuration files, headers, etc. It can also be useful as
56 a development and debugging tool for catching updates to variables that
57 should not be changed.
58
60 Readonly has the ability to create both deep and shallow readonly
61 variables.
62
63 If you pass a $ref, an @array or a %hash to corresponding functions
64 ::Scalar(), ::Array() and ::Hash(), then those functions recurse over
65 the data structure, marking everything as readonly. The entire
66 structure is then non-modifiable. This is normally what you want.
67
68 If you want only the top level to be readonly, use the alternate (and
69 poorly named) ::Scalar1(), ::Array1(), and ::Hash1() functions.
70
71 Plain Readonly() creates what the original author calls a "shallow"
72 readonly variable, which is great if you don't plan to use it on
73 anything but only one dimensional scalar values.
74
75 Readonly::Scalar() makes the variable 'deeply' readonly, so the
76 following snippet kills over as you expect:
77
78 use Readonly;
79
80 Readonly::Scalar my $ref => { 1 => 'a' };
81 $ref->{1} = 'b';
82 $ref->{2} = 'b';
83
84 While the following snippet does not make your structure 'deeply'
85 readonly:
86
87 use Readonly;
88
89 Readonly my $ref => { 1 => 'a' };
90 $ref->{1} = 'b';
91 $ref->{2} = 'b';
92
93
95 The following sections are updated versions of the previous authors
96 documentation.
97
98 Comparison with "use constant"
99 Perl provides a facility for creating constant values, via the constant
100 pragma. There are several problems with this pragma.
101
102 • The constants created have no leading sigils.
103
104 • These constants cannot be interpolated into strings.
105
106 • Syntax can get dicey sometimes. For example:
107
108 use constant CARRAY => (2, 3, 5, 7, 11, 13);
109 $a_prime = CARRAY[2]; # wrong!
110 $a_prime = (CARRAY)[2]; # right -- MUST use parentheses
111
112 • You have to be very careful in places where barewords are allowed.
113
114 For example:
115
116 use constant SOME_KEY => 'key';
117 %hash = (key => 'value', other_key => 'other_value');
118 $some_value = $hash{SOME_KEY}; # wrong!
119 $some_value = $hash{+SOME_KEY}; # right
120
121 (who thinks to use a unary plus when using a hash to scalarize the
122 key?)
123
124 • "use constant" works for scalars and arrays, not hashes.
125
126 • These constants are global to the package in which they're declared;
127 cannot be lexically scoped.
128
129 • Works only at compile time.
130
131 • Can be overridden:
132
133 use constant PI => 3.14159;
134 ...
135 use constant PI => 2.71828;
136
137 (this does generate a warning, however, if you have warnings
138 enabled).
139
140 • It is very difficult to make and use deep structures (complex data
141 structures) with "use constant".
142
144 Another popular way to create read-only scalars is to modify the symbol
145 table entry for the variable by using a typeglob:
146
147 *a = \'value';
148
149 This works fine, but it only works for global variables ("my" variables
150 have no symbol table entry). Also, the following similar constructs do
151 not work:
152
153 *a = [1, 2, 3]; # Does NOT create a read-only array
154 *a = { a => 'A'}; # Does NOT create a read-only hash
155
156 Pros
157 Readonly.pm, on the other hand, will work with global variables and
158 with lexical ("my") variables. It will create scalars, arrays, or
159 hashes, all of which look and work like normal, read-write Perl
160 variables. You can use them in scalar context, in list context; you can
161 take references to them, pass them to functions, anything.
162
163 Readonly.pm also works well with complex data structures, allowing you
164 to tag the whole structure as nonmodifiable, or just the top level.
165
166 Also, Readonly variables may not be reassigned. The following code will
167 die:
168
169 Readonly::Scalar $pi => 3.14159;
170 ...
171 Readonly::Scalar $pi => 2.71828;
172
173 Cons
174 Readonly.pm used to impose a performance penalty. It was pretty slow.
175 How slow? Run the "eg/benchmark.pl" script that comes with Readonly. On
176 my test system, "use constant" (const), typeglob constants (tglob),
177 regular read/write Perl variables (normal/literal), and the new
178 Readonly (ro/ro_simple) are all about the same speed, the old, tie
179 based Readonly.pm constants were about 1/22 the speed.
180
181 However, there is relief. There is a companion module available,
182 Readonly::XS. You won't need this if you're using Perl 5.8.x or
183 higher.
184
185 I repeat, you do not need Readonly::XS if your environment has perl
186 5.8.x or higher. Please see section entitled Internals for more.
187
189 Readonly::Scalar $var => $value;
190 Creates a nonmodifiable scalar, $var, and assigns a value of $value
191 to it. Thereafter, its value may not be changed. Any attempt to
192 modify the value will cause your program to die.
193
194 A value must be supplied. If you want the variable to have "undef"
195 as its value, you must specify "undef".
196
197 If $value is a reference to a scalar, array, or hash, then this
198 function will mark the scalar, array, or hash it points to as being
199 Readonly as well, and it will recursively traverse the structure,
200 marking the whole thing as Readonly. Usually, this is what you
201 want. However, if you want only the $value marked as Readonly, use
202 "Scalar1".
203
204 If $var is already a Readonly variable, the program will die with
205 an error about reassigning Readonly variables.
206
207 Readonly::Array @arr => (value, value, ...);
208 Creates a nonmodifiable array, @arr, and assigns the specified list
209 of values to it. Thereafter, none of its values may be changed; the
210 array may not be lengthened or shortened or spliced. Any attempt to
211 do so will cause your program to die.
212
213 If any of the values passed is a reference to a scalar, array, or
214 hash, then this function will mark the scalar, array, or hash it
215 points to as being Readonly as well, and it will recursively
216 traverse the structure, marking the whole thing as Readonly.
217 Usually, this is what you want. However, if you want only the hash
218 %@arr itself marked as Readonly, use "Array1".
219
220 If @arr is already a Readonly variable, the program will die with
221 an error about reassigning Readonly variables.
222
223 Readonly::Hash %h => (key => value, key => value, ...);
224 Readonly::Hash %h => {key => value, key => value, ...};
225 Creates a nonmodifiable hash, %h, and assigns the specified keys
226 and values to it. Thereafter, its keys or values may not be
227 changed. Any attempt to do so will cause your program to die.
228
229 A list of keys and values may be specified (with parentheses in the
230 synopsis above), or a hash reference may be specified (curly braces
231 in the synopsis above). If a list is specified, it must have an
232 even number of elements, or the function will die.
233
234 If any of the values is a reference to a scalar, array, or hash,
235 then this function will mark the scalar, array, or hash it points
236 to as being Readonly as well, and it will recursively traverse the
237 structure, marking the whole thing as Readonly. Usually, this is
238 what you want. However, if you want only the hash %h itself marked
239 as Readonly, use "Hash1".
240
241 If %h is already a Readonly variable, the program will die with an
242 error about reassigning Readonly variables.
243
244 Readonly $var => $value;
245 Readonly @arr => (value, value, ...);
246 Readonly %h => (key => value, ...);
247 Readonly %h => {key => value, ...};
248 Readonly $var;
249 The "Readonly" function is an alternate to the "Scalar", "Array",
250 and "Hash" functions. It has the advantage (if you consider it an
251 advantage) of being one function. That may make your program look
252 neater, if you're initializing a whole bunch of constants at once.
253 You may or may not prefer this uniform style.
254
255 It has the disadvantage of having a slightly different syntax for
256 versions of Perl prior to 5.8. For earlier versions, you must
257 supply a backslash, because it requires a reference as the first
258 parameter.
259
260 Readonly \$var => $value;
261 Readonly \@arr => (value, value, ...);
262 Readonly \%h => (key => value, ...);
263 Readonly \%h => {key => value, ...};
264
265 You may or may not consider this ugly.
266
267 Note that you can create implicit undefined variables with this
268 function like so "Readonly my $var;" while a verbose undefined
269 value must be passed to the standard "Scalar", "Array", and "Hash"
270 functions.
271
272 Readonly::Scalar1 $var => $value;
273 Readonly::Array1 @arr => (value, value, ...);
274 Readonly::Hash1 %h => (key => value, key => value, ...);
275 Readonly::Hash1 %h => {key => value, key => value, ...};
276 These alternate functions create shallow Readonly variables,
277 instead of deep ones. For example:
278
279 Readonly::Array1 @shal => (1, 2, {perl=>'Rules', java=>'Bites'}, 4, 5);
280 Readonly::Array @deep => (1, 2, {perl=>'Rules', java=>'Bites'}, 4, 5);
281
282 $shal[1] = 7; # error
283 $shal[2]{APL}='Weird'; # Allowed! since the hash isn't Readonly
284 $deep[1] = 7; # error
285 $deep[2]{APL}='Weird'; # error, since the hash is Readonly
286
288 When cloning using Storable or Clone you will notice that the value
289 stays readonly, which is correct. If you want to clone the value
290 without copying the readonly flag, use the "Clone" function:
291
292 Readonly::Scalar my $scalar => {qw[this that]};
293 # $scalar->{'eh'} = 'foo'; # Modification of a read-only value attempted
294 my $scalar_clone = Readonly::Clone $scalar;
295 $scalar_clone->{'eh'} = 'foo';
296 # $scalar_clone is now {this => 'that', eh => 'foo'};
297
298 The new variable ($scalar_clone) is a mutable clone of the original
299 $scalar.
300
302 These are a few very simple examples:
303
304 Scalars
305 A plain old read-only value
306
307 Readonly::Scalar $a => "A string value";
308
309 The value need not be a compile-time constant:
310
311 Readonly::Scalar $a => $computed_value;
312
313 Arrays/Lists
314 A read-only array:
315
316 Readonly::Array @a => (1, 2, 3, 4);
317
318 The parentheses are optional:
319
320 Readonly::Array @a => 1, 2, 3, 4;
321
322 You can use Perl's built-in array quoting syntax:
323
324 Readonly::Array @a => qw/1 2 3 4/;
325
326 You can initialize a read-only array from a variable one:
327
328 Readonly::Array @a => @computed_values;
329
330 A read-only array can be empty, too:
331
332 Readonly::Array @a => ();
333 Readonly::Array @a; # equivalent
334
335 Hashes
336 Typical usage:
337
338 Readonly::Hash %a => (key1 => 'value1', key2 => 'value2');
339
340 A read-only hash can be initialized from a variable one:
341
342 Readonly::Hash %a => %computed_values;
343
344 A read-only hash can be empty:
345
346 Readonly::Hash %a => ();
347 Readonly::Hash %a; # equivalent
348
349 If you pass an odd number of values, the program will die:
350
351 Readonly::Hash %a => (key1 => 'value1', "value2");
352 # This dies with "May not store an odd number of values in a hash"
353
355 Historically, this module exports the "Readonly" symbol into the
356 calling program's namespace by default. The following symbols are also
357 available for import into your program, if you like: "Scalar",
358 "Scalar1", "Array", "Array1", "Hash", and "Hash1".
359
361 Some people simply do not understand the relationship between this
362 module and Readonly::XS so I'm adding this section. Odds are, they
363 still won't understand but I like to write so...
364
365 In the past, Readonly's "magic" was performed by tie()-ing variables to
366 the "Readonly::Scalar", "Readonly::Array", and "Readonly::Hash"
367 packages (not to be confused with the functions of the same names) and
368 acting on "WRITE", "READ", et. al. While this worked well, it was slow.
369 Very slow. Like 20-30 times slower than accessing variables directly or
370 using one of the other const-related modules that have cropped up since
371 Readonly was released in 2003.
372
373 To 'fix' this, Readonly::XS was written. If installed, Readonly::XS
374 used the internal methods "SvREADONLY" and "SvREADONLY_on" to lock
375 simple scalars. On the surface, everything was peachy but things
376 weren't the same behind the scenes. In edge cases, code performed very
377 differently if Readonly::XS was installed and because it wasn't a
378 required dependency in most code, it made downstream bugs very hard to
379 track.
380
381 In the years since Readonly::XS was released, the then private internal
382 methods have been exposed and can be used in pure perl. Similar modules
383 were written to take advantage of this and a patch to Readonly was
384 created. We no longer need to build and install another module to make
385 Readonly useful on modern builds of perl.
386
387 • You do not need to install Readonly::XS.
388
389 • You should stop listing Readonly::XS as a dependency or expect it
390 to be installed.
391
392 • Stop testing the $Readonly::XSokay variable!
393
395 Please note that most users of Readonly no longer need to install the
396 companion module Readonly::XS which is recommended but not required for
397 perl 5.6.x and under. Please do not force it as a requirement in new
398 code and do not use the package variable $Readonly::XSokay in
399 code/tests. For more, see "Internals" in the section on Readonly's new
400 internals.
401
402 There are no non-core requirements.
403
405 If email is better for you, my address is mentioned below but I would
406 rather have bugs sent through the issue tracker found at
407 http://github.com/sanko/readonly/issues.
408
410 Thanks to Slaven Rezic for the idea of one common function (Readonly)
411 for all three types of variables (13 April 2002).
412
413 Thanks to Ernest Lergon for the idea (and initial code) for deeply-
414 Readonly data structures (21 May 2002).
415
416 Thanks to Damian Conway for the idea (and code) for making the Readonly
417 function work a lot smoother under perl 5.8+.
418
420 Sanko Robinson <sanko@cpan.org> - http://sankorobinson.com/
421
422 CPAN ID: SANKO
423
424 Original author: Eric J. Roode, roode@cpan.org
425
427 Copyright (C) 2013-2016 by Sanko Robinson <sanko@cpan.org>
428
429 Copyright (c) 2001-2004 by Eric J. Roode. All Rights Reserved.
430
431 This module is free software; you can redistribute it and/or modify it
432 under the same terms as Perl itself.
433
434
435
436perl v5.38.0 2023-07-21 Readonly(3pm)