1Config::Std(3) User Contributed Perl Documentation Config::Std(3)
2
3
4
6 Config::Std - Load and save configuration files in a standard format
7
9 This document describes Config::Std version 0.903
10
12 use Config::Std;
13
14 # Load named config file into specified hash...
15 read_config 'demo2.cfg' => my %config;
16
17 # Extract the value of a key/value pair from a specified section...
18 $config_value = $config{Section_label}{key};
19
20 # Change (or create) the value of a key/value pair...
21 $config{Other_section_label}{other_key} = $new_val;
22
23 # Update the config file from which this hash was loaded...
24 write_config %config;
25
26 # Write the config information to another file as well...
27 write_config %config, $other_file_name;
28
30 This module implements yet another damn configuration-file system.
31
32 The configuration language is deliberately simple and limited, and the
33 module works hard to preserve as much information (section order,
34 comments, etc.) as possible when a configuration file is updated.
35
36 The whole point of Config::Std is to encourage use of one standard
37 layout and syntax in config files. Damian says "I could have gotten
38 away with it, I would have only allowed one separator. But it proved
39 impossible to choose between ":" and "=" (half the people I asked
40 wanted one, half wanted the other)." Providing round-trip file re-
41 write is the spoonful of sugar to help the medicine go down. The
42 supported syntax is within the general INI file family
43
44 See Chapter 19 of "Perl Best Practices" (O'Reilly, 2005) for more
45 detail on the rationale for this approach.
46
47 Configuration language
48 The configuration language is a slight extension of the Windows INI
49 format.
50
51 Comments
52
53 A comment starts with a "#" character (Perl-style) or a ";" character
54 (INI-style), and runs to the end of the same line:
55
56 # This is a comment
57
58 ; Ywis, eke hight thilke
59
60 Comments can be placed almost anywhere in a configuration file, except
61 inside a section label, or in the key or value of a configuration
62 variable:
63
64 # Valid comment
65 [ # Not a comment, just a weird section label ]
66
67 ; Valid comment
68 key: value ; Not a comment, just part of the value
69
70 NOTE BENE -- that last is a BAD EXAMPLE of what is NOT supported. This
71 module supports full-line comments only, not on same line with semantic
72 content.
73
74 Sections
75
76 A configuration file consists of one or more sections, each of which is
77 introduced by a label in square brackets:
78
79 [SECTION1] # Almost anything is a valid section label
80
81 [SECTION 2] # Internal whitespace is allowed (except newlines)
82
83 [%^$%^&!!!] # The label doesn't have to be alphanumeric
84
85 [ETC. ETC. AS MANY AS YOU WANT]
86
87 The only restriction on section labels is that they must be by
88 themselves on a single line (except for any surrounding whitespace or
89 trailing comments), and they cannot contain the character "]".
90
91 Every line after a given section label until the next section label (or
92 the end of the config file) belongs to the given section label. If no
93 section label is currently in effect, the current section has an empty
94 label. In other words, there is an implicit:
95
96 [] # Label is the empty string
97
98 at the start of each config file.
99
100 Configuration variables
101
102 Each non-empty line within a section must consist of the specification
103 of a configuration variable. Each such variable consists of a key and a
104 string value. For example:
105
106 name: George
107 age: 47
108
109 his weight! : 185
110
111 The key consists of every character (including internal whitespace)
112 from the start of the line until the key/value separator. So, the
113 previous example declares three keys: 'name', 'age', and 'his weight!'.
114
115 Note that whitespace before and after the key is removed. This makes it
116 easier to format keys cleanly:
117
118 name : George
119 age : 47
120 his weight! : 185
121
122 The key/value separator can be either a colon (as above) or an equals
123 sign, like so:
124
125 name= George
126 age= 47
127 his weight! = 185
128
129 Both types of separators can be used in the same file, but neither can
130 be used as part of a key. Newlines are not allowed in keys either.
131
132 When writing out a config file, Config::Std tries to preserve whichever
133 separator was used in the original data (if that data was read in). New
134 data (created by code not parsed by "read_config") is written back with
135 a colon as its default separator, unless you specify the only other
136 separator value '=' when the module is loaded:
137
138 use Config::Std { def_sep => '=' };
139
140 Note that this does not change read-in parsing, does not change
141 punctuation for values that were parsed, and will not allow values
142 other than '=' or ':'.
143
144 Everything from the first non-whitespace character after the separator,
145 up to the end of the line, is treated as the value for the config
146 variable. So all of the above examples define the same three values:
147 'George', '47', and '185'.
148
149 In other words, any whitespace immediately surrounding the separator
150 character is part of the separator, not part of the key or value.
151
152 Note that you can't put a comment on the same line as a configuration
153 variable. The "# etc." is simply considered part of the value:
154
155 [Delimiters]
156
157 block delims: { }
158 string delims: " "
159 comment delims: # \n
160
161 You can comment a config var on the preceding or succeeding line:
162
163 [Delimiters]
164
165 # Use braces to delimit blocks...
166 block delims: { }
167
168 # Use double quotes to delimit strings
169
170 string delims: " "
171
172 # Use octothorpe/newline to delimit comments
173 comment delims: # \n
174
175 Multi-line configuration values
176
177 A single value can be continued over two or more lines. If the line
178 immediately after a configuration variable starts with the separator
179 character used in the variable's definition, then the value of the
180 variable continues on that line. For example:
181
182 address: 742 Evergreen Terrace
183 : Springfield
184 : USA
185
186 The newlines then form part of the value, so the value specified in the
187 previous example is: "742 Evergreen Terrace\nSpringfield\nUSA"
188
189 Note that the second and subsequent lines of a continued value are
190 considered to start where the whitespace after the original separator
191 finished, not where the whitespace after their own separator finishes.
192 For example, if the previous example had been:
193
194 address: 742 Evergreen Terrace
195 : Springfield
196 : USA
197
198 then the value would be:
199
200 "742 Evergreen Terrace\n Springfield\n USA"
201
202 If a continuation line has less leading whitespace that the first line:
203
204 address: 742 Evergreen Terrace
205 : Springfield
206 : USA
207
208 it's treated as having no leading whitespace:
209
210 "742 Evergreen Terrace\nSpringfield\nUSA"
211
212 Multi-part configuration values
213
214 If the particular key appears more than once in the same section, it is
215 considered to be part of the same configuration variable. The value of
216 that configuration value is then a list, containing all the individual
217 values for each instance of the key. For example, given the definition:
218
219 cast: Homer
220 cast: Marge
221 cast: Lisa
222 cast: Bart
223 cast: Maggie
224
225 the corresponding value of the 'cast' configuration variable is:
226 "['Homer', 'Marge', 'Lisa', 'Bart', 'Maggie']"
227
228 Individual values in a multi-part list can also be multi-line (see
229 above). For example, given:
230
231 extras: Moe
232 : (the bartender)
233
234 extras: Smithers
235 : (the dogsbody)
236
237 the value for the 'extras' config variable is:
238 "["Moe\n(the bartender)", "Smithers\n(the dogsbody)"]"
239
240 Internal representation
241 Each section label in a configuration file becomes a top-level hash key
242 whe the configuration file is read in. The corresponding value is a
243 nested hash reference.
244
245 Each configuration variable's key becomes a key in that nested hash
246 reference. Each configuration variable's value becomes the
247 corresponding value in that nested hash reference.
248
249 Single-line and multi-line values become strings. Multi-part values
250 become references to arrays of strings.
251
252 For example, the following configuration file:
253
254 # A simple key (just an identifier)...
255 simple : simple value
256
257 # A more complex key (with whitespace)...
258 more complex key : more complex value
259
260 # A new section...
261 [MULTI-WHATEVERS]
262
263 # A value spread over several lines...
264 multi-line : this is line 1
265 : this is line 2
266 : this is line 3
267
268 # Several values for the same key...
269 multi-value: this is value 1
270 multi-value: this is value 2
271 multi-value: this is value 3
272
273 would be read into a hash whose internal structure looked like this:
274
275 {
276 # Default section...
277 '' => {
278 'simple' => 'simple value',
279 'more complex key' => 'more complex value',
280 },
281
282 # Named section...
283 'MULTI-WHATEVERS' => {
284 'multi-line' => "this is line 1\nthis is line 2\nthis is line 3",
285
286 'multi-value' => [ 'this is value 1',
287 'this is value 2',
288 'this is value 3'
289 ],
290 }
291 }
292
294 The following subroutines are exported automatically whenever the
295 module is loaded...
296
297 "read_config($filename => %config_hash)"
298 "read_config($filename => $config_hash_ref)"
299 "read_config($string_ref => %config_hash_or_ref)"
300 The "read_config()" subroutine takes two arguments: the filename of
301 a configuration file, and a variable into which the contents of
302 that configuration file are to be loaded.
303
304 If the variable is a hash, then the configuration sections and
305 their key/value pairs are loaded into nested subhashes of the hash.
306
307 If the variable is a scalar with an undefined value, a reference to
308 an anonymous hash is first assigned to that scalar, and that hash
309 is then filled as described above.
310
311 The subroutine returns true on success, and throws an exception on
312 failure.
313
314 If you pass a reference to the string as the first argument to
315 "read_config()" it uses that string as the source of the config
316 info. For example:
317
318 use Config::Std;
319
320 # here we load the config text to a scalar
321 my $cfg = q{
322 [Section 1]
323 attr1 = at
324 attr2 = bat
325
326 [Section 2]
327 attr3 = cat
328 };
329
330 # here we parse the config from that scalar by passing a reference to it.
331 read_config( \$cfg, my %config );
332
333 use Data::Dumper 'Dumper';
334 warn Dumper [ \%config ];
335
336 "write_config(%config_hash => $filename)"
337 "write_config($config_hash_ref => $filename)"
338 "write_config(%config_hash)"
339 "write_config($config_hash_ref)"
340 The "write_config()" subroutine takes two arguments: the hash or
341 hash reference containing the configuration data to be written out
342 to disk, and an optional filename specifying which file it is to be
343 written to.
344
345 The data hash must conform to the two-level structure described
346 earlier: with top-level keys naming sections and their values being
347 references to second-level hashes that store the keys and values of
348 the configuartion variables. If the structure of the hash differs
349 from this, an exception is thrown.
350
351 If a filename is also specified, the subroutine opens that file and
352 writes to it. It no filename is specified, the subroutine uses the
353 name of the file from which the hash was originally loaded using
354 "read_config()". It no filename is specified and the hash wasn't
355 originally loaded using "read_config()", an exception is thrown.
356
357 The subroutine returns true on success and throws and exception on
358 failure.
359
360 If necessary (typically to avoid conflicts with other modules), you can
361 have the module export its two subroutines with different names by
362 loading it with the appropriate options:
363
364 use Config::Std { read_config => 'get_ini', write_config => 'update_ini' };
365
366 # and later...
367
368 get_ini($filename => %config_hash);
369
370 # and later still...
371
372 update_ini(%config_hash);
373
374 You can also control how much spacing the module puts between single-
375 line values when they are first written to a file, by using the
376 "def_gap" option:
377
378 # No empty line between single-line config values...
379 use Config::Std { def_gap => 0 };
380
381 # An empty line between all single-line config values...
382 use Config::Std { def_gap => 1 };
383
384 Regardless of the value passed for "def_gap", new multi-line values are
385 always written with an empty line above and below them. Likewise,
386 values that were previously read in from a file are always written back
387 with whatever spacing they originally had.
388
390 Can't open config file '%s' (%s)
391 You tried to read in a configuration file, but the file you
392 specified didn't exist. Perhaps the filepath you specified was
393 wrong. Or maybe your application didn't have permission to access
394 the file you specified.
395
396 Can't read from locked config file '$filename'
397 You tried to read in a configuration file, but the file you
398 specified was being written by someone else (they had a file lock
399 active on it). Either try again later, or work out who else is
400 using the file.
401
402 Scalar second argument to 'read_config' must be empty
403 You passed a scalar variable as the destination into
404 "read_config()" was supposed to load a configuration file, but that
405 variable already had a defined value, so "read_config()" couldn't
406 autovivify a new hash for you. Did you mean to pass the subroutine
407 a hash instead of a scalar?
408
409 Can't save %s value for key '%s' (only scalars or array refs)
410 You called "write_config" and passed it a hash containing a
411 configuration variable whose value wasn't a single string, or a
412 list of strings. The configuration file format supported by this
413 module only supports those two data types as values. If you really
414 need to store other kinds of data in a configuration file, you
415 should consider using "Data::Dumper" or "YAML" instead.
416
417 Missing filename in call to write_config()
418 You tried to calll "write_config()" with only a configuration hash,
419 but that hash wasn't originally loaded using "read_config()", so
420 "write_config()" has no idea where to write it to. Either make sure
421 the hash you're trying to save was originally loaded using
422 "read_config()", or else provide an explicit filename as the second
423 argument to "write_config()".
424
425 Can't open config file '%s' for writing (%s)
426 You tried to update or create a configuration file, but the file
427 you specified could not be opened for writing (for the reason given
428 in the parentheses). This is often caused by incorrect filepaths or
429 lack of write permissions on a directory.
430
431 Can't write to locked config file '%s'
432 You tried to update or create a configuration file, but the file
433 you specified was being written at the time by someone else (they
434 had a file lock active on it). Either try again later, or work out
435 who else is using the file.
436
438 Config::Std requires no configuration files or environment variables.
439 (To do so would be disturbingly recursive.)
440
442 This module requires the Class::Std module (available from the CPAN)
443
445 Those variants of INI file dialect supporting partial-line comment are
446 incompatible. (This is the price of keeping comments when re-writing.)
447
449 Memory leak re-reading
450 A daemon re-reading its config file has reported a memory leak.
451
452 Parallel testing not safe
453 This is a config file module. Tests written before "TAP" got
454 parallel testing are unsafe with parallel testing, surprise!
455 Settings are now included to force serial testing (until we
456 refactor all tests to use temp dirs?).
457
458 If using an older Perl < 5.21.1, and Module.PL, and getting out-of-
459 sequence test failures installing this module, either update
460 Test::Harness~'>= 3.31' or export HARNESS_OPTIONS=j1 (or
461 force/no-test, or use Build.PL and/or perl-5.22.0 or newer
462 instead).
463
464 Loading on demand
465 If you attempt to load "read_config()" and "write_config()" at
466 runtime with "require", you can not rely upon the prototype to
467 convert a regular hash to a reference. To work around this, you
468 must explicitly pass a reference to the config hash.
469
470 require Config::Std;
471 Config::Std->import;
472
473 my %config;
474 read_config($file, \%config);
475 write_config(\%config, $file);
476
477 Windows line endings on Unix/Linux (RT#21547/23550)
478 If the config file being read contains carriage returns and line
479 feeds at the end of each line rather than just line feeds (i.e. the
480 standard Windows file format, when read on a machine expecting
481 POSIX file format), Config::Std emits an error with embedded
482 newline.
483
484 Workaround is match file line-endings to locale.
485
486 This will be fixed in 1.000.
487
488 leading comment vanishes (RT#24597,)
489 A comment before the first section is not always retained on write-
490 back, if the '' default section is empty.
491
492 Please report any bugs or feature requests to
493 "bug-config-std@rt.cpan.org", or through the web interface at
494 <http://rt.cpan.org>.
495
497 Damian Conway "<DCONWAY@cpan.org>" Maintainers Bill Ricker
498 "<BRICKER@cpan.org>" Tom Metro "<tmetro@cpan.org>"
499
501 Copyright (c) 2005, Damian Conway "<DCONWAY@cpan.org>". Copyright (c)
502 2011,2014,2017, D.Conway, W.Ricker "<BRICKER@cpan.org>" All rights
503 reserved.
504
505 This module is free software; you can redistribute it and/or modify it
506 under the same terms as Perl itself.
507
509 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
510 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT
511 WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
512 PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND,
513 EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
514 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
515 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
516 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
517 NECESSARY SERVICING, REPAIR, OR CORRECTION.
518
519 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
520 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
521 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE
522 TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR
523 CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
524 SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
525 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
526 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
527 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
528 DAMAGES.
529
530
531
532perl v5.34.0 2022-01-21 Config::Std(3)