1Simple(3)             User Contributed Perl Documentation            Simple(3)
2
3
4

NAME

6       Config::Simple - simple configuration file class
7

SYNOPSIS

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
15         # --- OO interface:
16         $cfg = new Config::Simple('app.ini');
17
18         # accessing values:
19         $user = $cfg->param('User');
20
21         # getting the values as a hash:
22         %Config = $cfg->vars();
23
24         # updating value with a string
25         $cfg->param('User', 'sherzodR');
26
27         # updating a value with an array:
28         $cfg->param('Users', ['sherzodR', 'geek', 'merlyn']);
29
30         # adding a new block to an ini-file:
31         $cfg->param(-block=>'last-access', -values=>{'time'=>time()});
32
33         # accessing a block of an ini-file;
34         $mysql = $cfg->param(-block=>'mysql');
35
36         # saving the changes back to file:
37         $cfg->save();
38
39
40         # --- tie() interface
41         tie %Config, "Config::Simple", 'app.ini';
42

ABSTRACT

44       Reading and writing configuration files is one of the most frequent
45       tasks of any software design. Config::Simple is the library that helps
46       you with it.
47
48       Config::Simple is a class representing configuration file object.  It
49       supports several configuration file syntax and tries to identify the
50       file syntax automatically. Library supports parsing, updating and
51       creating configuration files.
52

ABOUT CONFIGURATION FILES

54       Keeping configurable variables in your program source code is ugly,
55       really.  And for people without much of a programming experience,
56       configuring your programs is like performing black magic. Besides, if
57       you need to access these values from within multiple files, want your
58       programs to be able to update configuration files or want to provide a
59       friendlier user interface for your configuration files, you just have
60       to store them in an external file. That's where Config::Simple comes
61       into play, making it very easy to read and write configuration files.
62
63       If you have never used configuration files before, here is a brief
64       overview of various syntax to choose from. Otherwise you can jump to
65       "PROGRAMMING STYLE".
66
67   SIMPLE CONFIGURATION FILE
68       Simple syntax is what you need for most of your projects. These are, as
69       the name asserts, the simplest. File consists of key/value pairs,
70       delimited by nothing but white space. Keys (variables) should be
71       strictly alpha-numeric with possible dashes (-). Values can hold any
72       arbitrary text. Here is an example of such a configuration file:
73
74         Alias     /exec
75         TempFile  /usr/tmp
76
77       Comments start with a pound ('#') sign and cannot share the same line
78       with other configuration data.
79
80   HTTP-LIKE SYNTAX
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       These configuration files are more native to Win32 systems. Data is
95       organized in blocks. Each key/value pair is delimited with an equal (=)
96       sign. Blocks are declared on their own lines enclosed in '[' and ']':
97
98         [BLOCK1]
99         KEY1=VALUE1
100         KEY2=VALUE2
101
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       These files are pretty much similar to traditional ini-files, except
124       they don't have any block declarations. This style is handy if you do
125       not want any categorization in your configuration file, but still want
126       to use '=' delimited key/value pairs.  While working with such files,
127       Config::Simple assigns them to a default block, called 'default' by
128       default :-).
129
130         url = "http://www.handalak.com"
131
132       Comments can begin with either pound ('#') or semi-colon (';'). Each
133       comment should reside on its own line
134

PROGRAMMING STYLE

136       Most of the programs simply need to be able to read settings from a
137       configuration file and assign them to a hash. If that's all you need,
138       you can simply use its import_from() - class method with the name of
139       the configuration file and a reference to an existing (possibly empty)
140       hash:
141
142         Config::Simple->import_from('myconf.cfg', \%Config);
143
144       Now your hash %Config holds all the configuration file's key/value
145       pairs.  Keys of a hash are variable names inside your configuration
146       file, and values are their respective values. If "myconf.cfg" was a
147       traditional ini-file, keys of the hash consist of block name and
148       variable delimited with a dot, such as "block.var".
149
150       If that's all you need, you can stop right here. Otherwise, read on.
151       There is much more Config::Simple offers.
152
153   READING THE CONFIGURATION FILE
154       To be able to use more features of the library, you will need to use
155       its object interface:
156
157         $cfg = new Config::Simple('app.cfg');
158
159       The above line reads and parses the configuration file accordingly.  It
160       tries to guess which syntax is used by passing the file to
161       guess_syntax() method.  Alternatively, you can create an empty object,
162       and only then read the configuration file in:
163
164         $cfg = new Config::Simple();
165         $cfg->read('app.cfg');
166
167       As in the first example, read() also calls guess_syntax() method on the
168       file.
169
170       If, for any reason, it fails to guess the syntax correctly (which is
171       less likely), you can try to debug by using its guess_syntax() method.
172       It expects file handle for a  configuration file and returns the name
173       of a syntax. Return value is one of "ini", "simple" or "http".
174
175         open(FH, "app.cfg");
176         printf("This file uses '%s' syntax\n", $cfg->guess_syntax(\*FH));
177
178   ACCESSING VALUES
179       After you read the configuration file in successfully, you can use
180       param() method to access the configuration values. For example:
181
182         $user = $cfg->param("User");
183
184       will return the value of "User" from either simple configuration file,
185       or http-styled configuration as well as simplified ini-files. To access
186       the value from a traditional ini-file, consider the following syntax:
187
188         $user = $cfg->param("mysql.user");
189
190       The above returns the value of "user" from within "[mysql]" block.
191       Notice the use of dot "." to delimit block and key names.
192
193       Config::Simple also supports vars() method, which, depending on the
194       context used, returns all the values either as hashref or hash:
195
196         my %Config = $cfg->vars();
197         print "Username: $Config{User}";
198
199         # If it was a traditional ini-file:
200         print "Username: $Config{'mysql.user'}";
201
202       If you call vars() in scalar context, you will end up with a reference
203       to a hash:
204
205         my $Config = $cfg->vars();
206         print "Username: $Config->{User}";
207
208       If you know what you're doing, you can also have an option of importing
209       all the names from the configuration file into your current name space
210       as global variables.  All the block/key names will be uppercased and
211       will be converted to Perl's valid variable names; that is, all the dots
212       (block-key separator) and other '\W' characters will be substituted
213       with underscore '_':
214
215         $cfg = new Config::Simple('app.cfg');
216         $cfg->import_names();
217
218         # or, with a single line:
219         Config::Simple->new('app.cfg')->import_names();
220
221         print STDERR "Debugging mode is on" if $DEBUG_MODE;
222
223       In the above example, if there was a variable 'mode' under '[debug]'
224       block, it will be now accessible via $DEBUG_MODE, as opposed to
225       $cfg->param('debug.mode');
226
227       import_names() by default imports the values to its caller's name
228       space.  Optionally, you can specify where to import the values by
229       passing the name of the name space as the first argument. It also
230       prevents potential name collisions:
231
232         Config::Simple->new('app.cfg')->import_names('CFG');
233         print STDERR "Debugging mode is on" if $CFG::DEBUG_MODE;
234
235       If all you want is to import values from a configuration file, the
236       above syntax may still seem longer than necessary. That's why
237       Config::Simple supports import_from() - class method, which is called
238       with the name of the configuration file. It will call import_names()
239       for you:
240
241         Config::Simple->import_from('app.cfg');
242
243       The above line imports all the variables into the caller's name space.
244       It's similar to calling import_names() on an object. If you pass a
245       string as the second argument, it will treat it as the alternative name
246       space to import the names into. As we already showed in the very first
247       example, you can also pass a reference to an existing hash as the
248       second argument. In this case, that hash will be modified with the
249       values of the configuration file.
250
251         # import into $CFG name space:
252         Config::Simple->import_from('app.cfg', 'CFG');
253
254         # import into %Config hash:
255         Config::Simple->import_from('app.cfg', \%Config);
256
257       The above line imports all the values to 'CFG' name space.
258       import_from() returns underlying Config::Simple object (which you may
259       not even need anymore):
260
261         $cfg = Config::Simple->import_from('app.cfg', \my %Config);
262         $cfg->write('app.cfg.bak');
263
264   UPDATING THE VALUES
265       Configuration values, once read into Config::Simple, can be updated
266       from within your program by using the same param() method used for
267       accessing them. For example:
268
269         $cfg->param("User", "sherzodR");
270
271       The above line changes the value of "User" to "sherzodR". Similar
272       syntax is applicable for ini-files as well:
273
274         $cfg->param("mysql.user", "sherzodR");
275
276       If the key you're trying to update does not exist, it will be created.
277       For example, to add a new "[session]" block to your ini-file, assuming
278       this block doesn't already exist:
279
280         $cfg->param("session.life", "+1M");
281
282       You can also delete values calling delete() method with the name of the
283       variable:
284
285         $cfg->delete('mysql.user'); # deletes 'user' under [mysql] block
286
287   SAVING/WRITING CONFIGURATION FILES
288       The above updates to the configuration values are in-memory operations.
289       They do not reflect in the file itself. To modify the files
290       accordingly, you need to call either "write()" or "save()" methods on
291       the object:
292
293         $cfg->write();
294
295       The above line writes the modifications to the configuration file.
296       Alternatively, you can pass a name to either write() or save() to
297       indicate the name of the file to create instead of modifying existing
298       configuration file:
299
300         $cfg->write("app.cfg.bak");
301
302       If you want the changes saved at all times, you can turn "autosave"
303       mode on by passing true value to $cfg->autosave(). It will make sure
304       before your program is terminated, all the configuration values are
305       written back to its file:
306
307         $cfg = new Config::Simple('aff.cfg');
308         $cfg->autosave(1);
309
310   CREATING CONFIGURATION FILES
311       Occasionally, your programs may want to create their own configuration
312       files on the fly, possibly from a user input. To create a configuration
313       file from scratch using Config::Simple, simply create an empty
314       configuration file object and define your syntax. You can do it by
315       either passing "syntax" option to new(), or by calling syntax() method.
316       Then play with param() method as you normally would.  When you're done,
317       call write() method with the name of the configuration file:
318
319         $cfg = new Config::Simple(syntax=>'ini');
320         # or you could also do:
321         # $cfg->autosave('ini')
322
323         $cfg->param("mysql.dsn", "DBI:mysql:db;host=handalak.com");
324         $cfg->param("mysql.user", "sherzodr");
325         $cfg->param("mysql.pass", 'marley01');
326         $cfg->param("site.title", 'sherzodR "The Geek"');
327         $cfg->write("new.cfg");
328
329       This creates a file "new.cfg" with the following content:
330
331         ; Config::Simple 4.43
332         ; Sat Mar  8 00:32:49 2003
333
334         [site]
335         title=sherzodR "The Geek"
336
337         [mysql]
338         pass=marley01
339         dsn=DBI:mysql:db;host=handalak.com
340         user=sherzodr
341
342       Neat, huh? Supported syntax keywords are "ini", "simple" or "http".
343       Currently there is no support for creating simplified ini-files.
344
345   MULTIPLE VALUES
346       Ever wanted to define array of values in your single configuration
347       variable? I have!  That's why Config::Simple supports this fancy
348       feature as well. Simply separate your values with a comma:
349
350         Files hp.cgi, template.html, styles.css
351
352       Now param() method returns an array of values:
353
354         @files = $cfg->param("Files");
355         unlink $_ for @files;
356
357       If you want a comma as part of a value, enclose the value(s) in double
358       quotes:
359
360         CVSFiles "hp.cgi,v", "template.html,v", "styles.css,v"
361
362       In case you want either of the values to hold literal quote ("), you
363       can escape it with a backlash:
364
365         SiteTitle "sherzod \"The Geek\""
366
367   TIE INTERFACE
368       If OO style intimidates you, and import_from() is too simple for you,
369       Config::Simple also supports tie() interface. This interface allows you
370       to tie() an ordinary Perl hash to the configuration file. From that
371       point on, you can use the variable as an ordinary Perl hash.
372
373         tie %Config, "Config::Simple", 'app.cfg';
374
375         # Using %Config as an ordinary hash
376         print "Username is '$Config{User}'\n";
377         $Config{User} = 'sherzodR';
378
379       The difference between "import_from($file, \%Hash)" is, all the changes
380       you make to the hash after tie()ing it, will also reflect in the
381       configuration file object.  If autosave() was turned on, they will also
382       be written back to file:
383
384         tie %Config, "Config::Simple", "app.cfg";
385         tied(%Config)->autosave(1);
386
387       To access the method provided in OO syntax, you need to get underlying
388       Config::Simple object. You can do so with tied() function:
389
390         tied(%Config)->write();
391
392       WARNING: tie interface is experimental and not well tested yet. Let me
393       know if you encounter a problem.
394

MISCELLANEOUS

396   CASE SENSITIVITY
397       By default, configuration file keys and values are case sensitive.
398       Which means, $cfg->param("User") and $cfg->param("user") are referring
399       to two different values.  But it is possible to force Config::Simple to
400       ignore cases all together by enabling "-lc" switch while loading the
401       library:
402
403         use Config::Simple ('-lc');
404
405       WARNING: If you call write() or save(), while working on "-lc" mode,
406       all the case information of the original file will be lost. So use it
407       if you know what you're doing.
408
409   USING QUOTES
410       Some people suggest if values consist of none alpha-numeric strings,
411       they should be enclosed in double quotes. Well, says them! Although
412       Config::Simple supports parsing such configuration files already, it
413       doesn't follow this rule while writing them.  If you really need it to
414       generate such compatible configuration files, "-strict" switch is what
415       you need:
416
417         use Config::Simple '-strict';
418
419       Now, when you write the configuration data back to files, if values
420       hold any none alpha-numeric strings, they will be quoted accordingly.
421       All the double quotes that are part of the value will be escaped with a
422       backslash.
423
424   EXCEPTION HANDLING
425       Config::Simple doesn't believe in dying that easily (unless you insult
426       it using wrong syntax).  It leaves the decision to the programmer
427       implementing the library. You can use its error() - class method to
428       access underlying error message. Methods that require you to check for
429       their return values are read() and write(). If you pass filename to
430       new(), you will need to check its return value as well. They return any
431       true value indicating success, undef otherwise:
432
433         # following new() always returns true:
434         $cfg = new Config::Simple();
435
436         # read() can fail:
437         $cfg->read('app.cfg') or die $cfg->error();
438
439         # following new() can fail:
440         $cfg = new Config::Simple('app.cfg') or die Config::Simple->error();
441
442         # import_from() calls read(), so it can fail:
443         Config::Simple->import_from('app.cfg', \%Config) or die Config::Simple->error();
444
445         # write() may fail:
446         $cfg->write() or die $cfg->error();
447
448         # tie() may fail, since it calls new() with a filename
449         tie %Config, "Config::Simple", 'app.cfg' or die Config::Simple->error();
450

METHODS

452       new()
453           - constructor. Optionally accepts several arguments. Returns
454           Config::Simple object.  Supported arguments are filename, syntax,
455           autosave. If there is a single argument, will be treated as the
456           name of the configuration file.
457
458       autosave([$bool])
459           - turns 'autosave' mode on if passed true argument. Returns current
460           autosave mode if used without arguments. In 'autosave' mode
461           Config::Simple writes all the changes back to its file without you
462           having to call write() or save()
463
464       read()
465           - accepts name  of the configuration file to parse. Before that, it
466           tries to guess the syntax of the file by calling guess_syntax()
467           method. Then calls either of parse_ini_file(), parse_cfg_file() or
468           parse_http_file() accordingly. If the name of the file is provided
469           to the constructor - new(), there is no need to call read().
470
471       param([$name], [$value])
472           - used for accessing and updating configuration variables. If used
473           with no arguments returns all the available names from the
474           configuration file.
475
476       delete($name)
477           - deletes a variable from a configuration file. $name has the same
478           meaning and syntax as it does in param($name)
479
480       clear()
481           - clears all the data from the object. Calling save() or turning
482           autosave() on results in an empty configuration file as well.
483
484       vars()
485           - depending on the context used, returns all the values available
486           in the configuration file either as a hash or a reference to a hash
487
488       import_names([$NS])
489           - imports all the names from the configuration file to the caller's
490           name space. Optional argument, if passed, will be treated as the
491           name space variables to be imported into.  All the names will be
492           uppercased. Non-alphanumeric strings in the values will be
493           underscored
494
495       import_from($file, \%hash | $NS)
496           - class method. If the second argument is a reference to an
497           existing hash, it will load all the configuration contents into
498           that hash. If the second argument is a string, it will be treated
499           as the name space variables should be imported into, just like
500           import_names() does.
501
502       get_block($name)
503           is mostly used for accessing blocks in ini-styled configuration
504           files.  Returns a hashref of all the key/value pairs of a given
505           block. Also supported by param() method with the help of "-block"
506           option:
507
508             $hash = $cfg->get_block('Project');
509             # is the same as saying:
510             $hash = $cfg->param(-block=>'Project');
511
512       set_block($name, $values)
513           used in assigning contents to a block in ini-styled configuration
514           files. $name should be the name of a [block], and $values is
515           assumed to be a hashref mapping key/value pairs.  Also supported by
516           param() method with the help of "-block" and "-value" (or
517           "-values") options:
518
519             $cfg->set_block('Project', {Count=>3, 'Multiple Column' => 20});
520             # is the same as:
521             $cfg->param(-block=>'Project', -value=>{Count=>3, 'Multiple Column' => 20});
522
523           Warning: all the contents of a block, if previously existed will be
524           wiped out.  If you want to set specific key/value pairs, use
525           explicit method:
526
527             $cfg->param('Project.Count', 3);
528
529       as_string()
530           - returns the configuration file as a chunk of text. It is the same
531           text used by write() and save() to store the new configuration file
532           back to file.
533
534       write()
535           - writes the configuration file into disk. Argument, if passed,
536           will be treated as the name of the file configuration variables
537           should be saved in.
538
539       save()
540           - same as write().
541
542       dump()
543           - for debugging only. Dumps the whole Config::Simple object using
544           Data::Dumper.  Argument, if passed, will be treated as the name of
545           the file object should be dumped in.  The second argument specifies
546           amount of indentation as documented in Data::Dumper manual. Default
547           indent size is 2.
548
549       error()
550           - returns the last error message from read/write or import_*
551           operations.
552

TODO

554       •   Support for lines with continuation character, '\'. Currently its
555           support is restricted and quite possibly buggy.
556
557       •   Retaining comments while writing the configuration files back
558           and/or methods for manipulating comments. Everyone loves comments!
559
560       •   Retain the order of the blocks and other variables in the
561           configuration files.
562

BUGS

564       Submit bugs and possibly patches to Sherzod B. Ruzmetov
565       <sherzodr@cpan.org>.
566

CREDITS

568       Michael Caldwell (mjc@mjcnet.com)
569           whitespace support, "-lc" switch and for various bug fixes
570
571       Scott Weinstein (Scott.Weinstein@lazard.com)
572           bug fix in TIEHASH
573
574       Ruslan U. Zakirov <cubic@wr.miee.ru>
575           default name space suggestion and patch
576
577       Hirosi Taguti
578           import_names() and import_from() idea.
579
580       Vitaly Kushneriuk
581           for bug fixes and suggestions
582
584         Copyright (C) 2002-2003 Sherzod B. Ruzmetov.
585
586         This software is free library. You can modify and/or distribute it
587         under the same terms as Perl itself
588

AUTHOR

590         Sherzod B. Ruzmetov E<lt>sherzodr@cpan.orgE<gt>
591         URI: http://author.handalak.com
592

SEE ALSO

594       Config::General, Config::Simple, Config::Tiny
595
596
597
598perl v5.36.0                      2023-01-20                         Simple(3)
Impressum