1Simple(3) User Contributed Perl Documentation Simple(3)
2
3
4
6 Config::Simple - simple configuration file class
7
9 use Config::Simple;
10
11 # --- Simple usage. Loads the config. file into a hash:
12 Config::Simple->import_from('app.ini', \%Config);
13
14 # --- OO interface:
15 $cfg = new Config::Simple('app.ini');
16
17 # accessing values:
18 $user = $cfg->param('User');
19
20 # getting the values as a hash:
21 %Config = $cfg->vars();
22
23 # updating value with a string
24 $cfg->param('User', 'sherzodR');
25
26 # updating a value with an array:
27 $cfg->param('Users', ['sherzodR', 'geek', 'merlyn']);
28
29 # adding a new block to an ini-file:
30 $cfg->param(-block=>'last-access', -values=>{'time'=>time()});
31
32 # accessing a block of an ini-file;
33 $mysql = $cfg->param(-block=>'mysql');
34
35 # saving the changes back to file:
36 $cfg->save();
37
38 # --- tie() interface
39 tie %Config, "Config::Simple", 'app.ini';
40
42 Reading and writing configuration files is one of the most frequent
43 tasks of any software design. Config::Simple is the library that helps
44 you with it.
45
46 Config::Simple is a class representing configuration file object. It
47 supports several configuration file syntax and tries to identify the
48 file syntax automatically. Library supports parsing, updating and cre‐
49 ating configuration files.
50
52 Keeping configurable variables in your program source code is ugly,
53 really. And for people without much of a programming experience, con‐
54 figuring your programs is like performing black magic. Besides, if you
55 need to access these values from within multiple files, want your pro‐
56 grams to be able to update configuration files or want to provide a
57 friendlier user interface for your configuration files, you just have
58 to store them in an external file. That's where Config::Simple comes
59 into play, making it very easy to read and write configuration files.
60
61 If you have never used configuration files before, here is a brief
62 overview of various syntax to choose from. Otherwise you can jump to
63 "PROGRAMMING STYLE".
64
65 SIMPLE CONFIGURATION FILE
66
67 Simple syntax is what you need for most of your projects. These are, as
68 the name asserts, the simplest. File consists of key/value pairs,
69 delimited by nothing but white space. Keys (variables) should be
70 strictly alpha-numeric with possible dashes (-). Values can hold any
71 arbitrary text. Here is an example of such a configuration file:
72
73 Alias /exec
74 TempFile /usr/tmp
75
76 Comments start with a pound ('#') sign and cannot share the same line
77 with other configuration data.
78
79 HTTP-LIKE SYNTAX
80
81 This format of separating key/value pairs is used by HTTP messages.
82 Each key/value is separated by semi-colon (:). Keys are alphanumeric
83 strings with possible '-'. Values can be any arbitrary text:
84
85 Example:
86
87 Alias: /exec
88 TempFile: /usr/tmp
89
90 It is OK to have spaces around ':'. Comments start with '#' and cannot
91 share the same line with other configuration data.
92
93 INI-FILE
94
95 These configuration files are more native to Win32 systems. Data is
96 organized in blocks. Each key/value pair is delimited with an equal (=)
97 sign. Blocks are declared on their own lines enclosed in '[' and ']':
98
99 [BLOCK1]
100 KEY1=VALUE1
101 KEY2=VALUE2
102
103 [BLOCK2]
104 KEY1=VALUE1
105 KEY2=VALUE2
106
107 Your Winamp 2.x play list is an example of such a configuration file.
108
109 This is the perfect choice if you need to organize your configuration
110 file into categories:
111
112 [site]
113 url="http://www.handalak.com"
114 title="Web site of a \"Geek\""
115 author=sherzodr
116
117 [mysql]
118 dsn="dbi:mysql:db_name;host=handalak.com"
119 user=sherzodr
120 password=marley01
121
122 SIMPLIFIED INI-FILE
123
124 These files are pretty much similar to traditional ini-files, except
125 they don't have any block declarations. This style is handy if you do
126 not want any categorization in your configuration file, but still want
127 to use '=' delimited key/value pairs. While working with such files,
128 Config::Simple assigns them to a default block, called 'default' by
129 default :-).
130
131 url = "http://www.handalak.com"
132
133 Comments can begin with either pound ('#') or semi-colon (';'). Each
134 comment should reside on its own line
135
137 Most of the programs simply need to be able to read settings from a
138 configuration file and assign them to a hash. If that's all you need,
139 you can simply use its import_from() - class method with the name of
140 the configuration file and a reference to an existing (possibly empty)
141 hash:
142
143 Config::Simple->import_from('myconf.cfg', \%Config);
144
145 Now your hash %Config holds all the configuration file's key/value
146 pairs. Keys of a hash are variable names inside your configuration
147 file, and values are their respective values. If "myconf.cfg" was a
148 traditional ini-file, keys of the hash consist of block name and vari‐
149 able delimited with a dot, such as "block.var".
150
151 If that's all you need, you can stop right here. Otherwise, read on.
152 There is much more Config::Simple offers.
153
154 READING THE CONFIGURATION FILE
155
156 To be able to use more features of the library, you will need to use
157 its object interface:
158
159 $cfg = new Config::Simple('app.cfg');
160
161 The above line reads and parses the configuration file accordingly. It
162 tries to guess which syntax is used by passing the file to guess_syn‐
163 tax() method. Alternatively, you can create an empty object, and only
164 then read the configuration file in:
165
166 $cfg = new Config::Simple();
167 $cfg->read('app.cfg');
168
169 As in the first example, read() also calls guess_syntax() method on the
170 file.
171
172 If, for any reason, it fails to guess the syntax correctly (which is
173 less likely), you can try to debug by using its guess_syntax() method.
174 It expects file handle for a configuration file and returns the name
175 of a syntax. Return value is one of "ini", "simple" or "http".
176
177 open(FH, "app.cfg");
178 printf("This file uses '%s' syntax\n", $cfg->guess_syntax(\*FH));
179
180 ACCESSING VALUES
181
182 After you read the configuration file in successfully, you can use
183 param() method to access the configuration values. For example:
184
185 $user = $cfg->param("User");
186
187 will return the value of "User" from either simple configuration file,
188 or http-styled configuration as well as simplified ini-files. To access
189 the value from a traditional ini-file, consider the following syntax:
190
191 $user = $cfg->param("mysql.user");
192
193 The above returns the value of "user" from within "[mysql]" block.
194 Notice the use of dot "." to delimit block and key names.
195
196 Config::Simple also supports vars() method, which, depending on the
197 context used, returns all the values either as hashref or hash:
198
199 my %Config = $cfg->vars();
200 print "Username: $Config{User}";
201
202 # If it was a traditional ini-file:
203 print "Username: $Config{'mysql.user'}";
204
205 If you call vars() in scalar context, you will end up with a reference
206 to a hash:
207
208 my $Config = $cfg->vars();
209 print "Username: $Config->{User}";
210
211 If you know what you're doing, you can also have an option of importing
212 all the names from the configuration file into your current name space
213 as global variables. All the block/key names will be uppercased and
214 will be converted to Perl's valid variable names; that is, all the dots
215 (block-key separator) and other '\W' characters will be substituted
216 with underscore '_':
217
218 $cfg = new Config::Simple('app.cfg');
219 $cfg->import_names();
220
221 # or, with a single line:
222 Config::Simple->new('app.cfg')->import_names();
223
224 print STDERR "Debugging mode is on" if $DEBUG_MODE;
225
226 In the above example, if there was a variable 'mode' under '[debug]'
227 block, it will be now accessible via $DEBUG_MODE, as opposed to
228 $cfg->param('debug.mode');
229
230 "import_names()" by default imports the values to its caller's name
231 space. Optionally, you can specify where to import the values by pass‐
232 ing the name of the name space as the first argument. It also prevents
233 potential name collisions:
234
235 Config::Simple->new('app.cfg')->import_names('CFG');
236 print STDERR "Debugging mode is on" if $CFG::DEBUG_MODE;
237
238 If all you want is to import values from a configuration file, the
239 above syntax may still seem longer than necessary. That's why Con‐
240 fig::Simple supports import_from() - class method, which is called with
241 the name of the configuration file. It will call import_names() for
242 you:
243
244 Config::Simple->import_from('app.cfg');
245
246 The above line imports all the variables into the caller's name space.
247 It's similar to calling import_names() on an object. If you pass a
248 string as the second argument, it will treat it as the alternative name
249 space to import the names into. As we already showed in the very first
250 example, you can also pass a reference to an existing hash as the sec‐
251 ond argument. In this case, that hash will be modified with the values
252 of the configuration file.
253
254 # import into $CFG name space:
255 Config::Simple->import_from('app.cfg', 'CFG');
256
257 # import into %Config hash:
258 Config::Simple->import_from('app.cfg', \%Config);
259
260 The above line imports all the values to 'CFG' name space.
261 import_from() returns underlying Config::Simple object (which you may
262 not even need anymore):
263
264 $cfg = Config::Simple->import_from('app.cfg', \my %Config);
265 $cfg->write('app.cfg.bak');
266
267 UPDATING THE VALUES
268
269 Configuration values, once read into Config::Simple, can be updated
270 from within your program by using the same param() method used for
271 accessing them. For example:
272
273 $cfg->param("User", "sherzodR");
274
275 The above line changes the value of "User" to "sherzodR". Similar syn‐
276 tax is applicable for ini-files as well:
277
278 $cfg->param("mysql.user", "sherzodR");
279
280 If the key you're trying to update does not exist, it will be created.
281 For example, to add a new "[session]" block to your ini-file, assuming
282 this block doesn't already exist:
283
284 $cfg->param("session.life", "+1M");
285
286 You can also delete values calling delete() method with the name of the
287 variable:
288
289 $cfg->delete('mysql.user'); # deletes 'user' under [mysql] block
290
291 SAVING/WRITING CONFIGURATION FILES
292
293 The above updates to the configuration values are in-memory operations.
294 They do not reflect in the file itself. To modify the files accord‐
295 ingly, you need to call either "write()" or "save()" methods on the
296 object:
297
298 $cfg->write();
299
300 The above line writes the modifications to the configuration file.
301 Alternatively, you can pass a name to either write() or save() to indi‐
302 cate the name of the file to create instead of modifying existing con‐
303 figuration file:
304
305 $cfg->write("app.cfg.bak");
306
307 If you want the changes saved at all times, you can turn "autosave"
308 mode on by passing true value to $cfg->autosave(). It will make sure
309 before your program is terminated, all the configuration values are
310 written back to its file:
311
312 $cfg = new Config::Simple('aff.cfg');
313 $cfg->autosave(1);
314
315 CREATING CONFIGURATION FILES
316
317 Occasionally, your programs may want to create their own configuration
318 files on the fly, possibly from a user input. To create a configuration
319 file from scratch using Config::Simple, simply create an empty configu‐
320 ration file object and define your syntax. You can do it by either
321 passing "syntax" option to new(), or by calling syntax() method. Then
322 play with param() method as you normally would. When you're done, call
323 write() method with the name of the configuration file:
324
325 $cfg = new Config::Simple(syntax=>'ini');
326 # or you could also do:
327 # $cfg->autosave('ini')
328
329 $cfg->param("mysql.dsn", "DBI:mysql:db;host=handalak.com");
330 $cfg->param("mysql.user", "sherzodr");
331 $cfg->param("mysql.pass", 'marley01');
332 $cfg->param("site.title", 'sherzodR "The Geek"');
333 $cfg->write("new.cfg");
334
335 This creates a file "new.cfg" with the following content:
336
337 ; Config::Simple 4.43
338 ; Sat Mar 8 00:32:49 2003
339
340 [site]
341 title=sherzodR "The Geek"
342
343 [mysql]
344 pass=marley01
345 dsn=DBI:mysql:db;host=handalak.com
346 user=sherzodr
347
348 Neat, huh? Supported syntax keywords are "ini", "simple" or "http".
349 Currently there is no support for creating simplified ini-files.
350
351 MULTIPLE VALUES
352
353 Ever wanted to define array of values in your single configuration
354 variable? I have! That's why Config::Simple supports this fancy fea‐
355 ture as well. Simply separate your values with a comma:
356
357 Files hp.cgi, template.html, styles.css
358
359 Now param() method returns an array of values:
360
361 @files = $cfg->param("Files");
362 unlink $_ for @files;
363
364 If you want a comma as part of a value, enclose the value(s) in double
365 quotes:
366
367 CVSFiles "hp.cgi,v", "template.html,v", "styles.css,v"
368
369 In case you want either of the values to hold literal quote ("), you
370 can escape it with a backlash:
371
372 SiteTitle "sherzod \"The Geek\""
373
374 TIE INTERFACE
375
376 If OO style intimidates you, and "import_from()" is too simple for you,
377 Config::Simple also supports tie() interface. This interface allows you
378 to tie() an ordinary Perl hash to the configuration file. From that
379 point on, you can use the variable as an ordinary Perl hash.
380
381 tie %Config, "Config::Simple", 'app.cfg';
382
383 # Using %Config as an ordinary hash
384 print "Username is '$Config{User}'\n";
385 $Config{User} = 'sherzodR';
386
387 The difference between "import_from($file, \%Hash)" is, all the changes
388 you make to the hash after tie()ing it, will also reflect in the con‐
389 figuration file object. If autosave() was turned on, they will also be
390 written back to file:
391
392 tie %Config, "Config::Simple", "app.cfg";
393 tied(%Config)->autosave(1);
394
395 To access the method provided in OO syntax, you need to get underlying
396 Config::Simple object. You can do so with tied() function:
397
398 tied(%Config)->write();
399
400 WARNING: tie interface is experimental and not well tested yet. Let me
401 know if you encounter a problem.
402
404 CASE SENSITIVITY
405
406 By default, configuration file keys and values are case sensitive.
407 Which means, $cfg->param("User") and $cfg->param("user") are referring
408 to two different values. But it is possible to force Config::Simple to
409 ignore cases all together by enabling "-lc" switch while loading the
410 library:
411
412 use Config::Simple ('-lc');
413
414 WARNING: If you call write() or save(), while working on "-lc" mode,
415 all the case information of the original file will be lost. So use it
416 if you know what you're doing.
417
418 USING QUOTES
419
420 Some people suggest if values consist of none alpha-numeric strings,
421 they should be enclosed in double quotes. Well, says them! Although
422 Config::Simple supports parsing such configuration files already, it
423 doesn't follow this rule while writing them. If you really need it to
424 generate such compatible configuration files, "-strict" switch is what
425 you need:
426
427 use Config::Simple '-strict';
428
429 Now, when you write the configuration data back to files, if values
430 hold any none alpha-numeric strings, they will be quoted accordingly.
431 All the double quotes that are part of the value will be escaped with a
432 backslash.
433
434 EXCEPTION HANDLING
435
436 Config::Simple doesn't believe in dying that easily (unless you insult
437 it using wrong syntax). It leaves the decision to the programmer
438 implementing the library. You can use its error() - class method to
439 access underlying error message. Methods that require you to check for
440 their return values are read() and write(). If you pass filename to
441 new(), you will need to check its return value as well. They return any
442 true value indicating success, undef otherwise:
443
444 # following new() always returns true:
445 $cfg = new Config::Simple();
446
447 # read() can fail:
448 $cfg->read('app.cfg') or die $cfg->error();
449
450 # following new() can fail:
451 $cfg = new Config::Simple('app.cfg') or die Config::Simple->error();
452
453 # import_from() calls read(), so it can fail:
454 Config::Simple->import_from('app.cfg', \%Config) or die Config::Simple->error();
455
456 # write() may fail:
457 $cfg->write() or die $cfg->error();
458
459 # tie() may fail, since it calls new() with a filename
460 tie %Config, "Config::Simple", 'app.cfg' or die Config::Simple->error();
461
463 new()
464 - constructor. Optionally accepts several arguments. Returns Con‐
465 fig::Simple object. Supported arguments are filename, syntax,
466 autosave. If there is a single argument, will be treated as the
467 name of the configuration file.
468
469 autosave([$bool])
470 - turns 'autosave' mode on if passed true argument. Returns current
471 autosave mode if used without arguments. In 'autosave' mode Con‐
472 fig::Simple writes all the changes back to its file without you
473 having to call write() or save()
474
475 read()
476 - accepts name of the configuration file to parse. Before that, it
477 tries to guess the syntax of the file by calling guess_syntax()
478 method. Then calls either of parse_ini_file(), parse_cfg_file() or
479 parse_http_file() accordingly. If the name of the file is provided
480 to the constructor - new(), there is no need to call read().
481
482 param([$name], [$value])
483 - used for accessing and updating configuration variables. If used
484 with no arguments returns all the available names from the configu‐
485 ration file.
486
487 delete($name)
488 - deletes a variable from a configuration file. $name has the same
489 meaning and syntax as it does in param($name)
490
491 clear()
492 - clears all the data from the object. Calling save() or turning
493 autosave() on results in an empty configuration file as well.
494
495 vars()
496 - depending on the context used, returns all the values available
497 in the configuration file either as a hash or a reference to a hash
498
499 import_names([$NS])
500 - imports all the names from the configuration file to the caller's
501 name space. Optional argument, if passed, will be treated as the
502 name space variables to be imported into. All the names will be
503 uppercased. Non-alphanumeric strings in the values will be under‐
504 scored
505
506 import_from($file, \%hash ⎪ $NS)
507 - class method. If the second argument is a reference to an exist‐
508 ing hash, it will load all the configuration contents into that
509 hash. If the second argument is a string, it will be treated as the
510 name space variables should be imported into, just like
511 import_names() does.
512
513 get_block($name)
514 is mostly used for accessing blocks in ini-styled configuration
515 files. Returns a hashref of all the key/value pairs of a given
516 block. Also supported by param() method with the help of "-block"
517 option:
518
519 $hash = $cfg->get_block('Project');
520 # is the same as saying:
521 $hash = $cfg->param(-block=>'Project');
522
523 set_block($name, $values)
524 used in assigning contents to a block in ini-styled configuration
525 files. $name should be the name of a [block], and $values is
526 assumed to be a hashref mapping key/value pairs. Also supported by
527 param() method with the help of "-block" and "-value" (or "-val‐
528 ues") options:
529
530 $cfg->set_block('Project', {Count=>3, 'Multiple Column' => 20});
531 # is the same as:
532 $cfg->param(-block=>'Project', -value=>{Count=>3, 'Multiple Column' => 20});
533
534 Warning: all the contents of a block, if previously existed will be
535 wiped out. If you want to set specific key/value pairs, use
536 explicit method:
537
538 $cfg->param('Project.Count', 3);
539
540 as_string()
541 - returns the configuration file as a chunk of text. It is the same
542 text used by write() and save() to store the new configuration file
543 back to file.
544
545 write()
546 - writes the configuration file into disk. Argument, if passed,
547 will be treated as the name of the file configuration variables
548 should be saved in.
549
550 save()
551 - same as write().
552
553 dump()
554 - for debugging only. Dumps the whole Config::Simple object using
555 Data::Dumper. Argument, if passed, will be treated as the name of
556 the file object should be dumped in. The second argument specifies
557 amount of indentation as documented in Data::Dumper manual. Default
558 indent size is 2.
559
560 error()
561 - returns the last error message from read/write or import_* opera‐
562 tions.
563
565 · Support for lines with continuation character, '\'. Currently its
566 support is restricted and quite possibly buggy.
567
568 · Retaining comments while writing the configuration files back
569 and/or methods for manipulating comments. Everyone loves comments!
570
571 · Retain the order of the blocks and other variables in the configu‐
572 ration files.
573
575 Submit bugs and possibly patches to Sherzod B. Ruzmetov <sher‐
576 zodr@cpan.org>.
577
579 Michael Caldwell (mjc@mjcnet.com)
580 whitespace support, "-lc" switch and for various bug fixes
581
582 Scott Weinstein (Scott.Weinstein@lazard.com)
583 bug fix in TIEHASH
584
585 Ruslan U. Zakirov <cubic@wr.miee.ru>
586 default name space suggestion and patch
587
588 Hirosi Taguti
589 import_names() and import_from() idea.
590
591 Vitaly Kushneriuk
592 for bug fixes and suggestions
593
595 Copyright (C) 2002-2003 Sherzod B. Ruzmetov.
596
597 This software is free library. You can modify and/or distribute it
598 under the same terms as Perl itself
599
601 Sherzod B. Ruzmetov E<lt>sherzodr@cpan.orgE<gt>
602 URI: http://author.handalak.com
603
605 Config::General, Config::Simple, Config::Tiny
606
607
608
609perl v5.8.8 2006-09-12 Simple(3)