Debian Codegraph @

README

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