Simple(3)
π NAME π
Config::Simple - simple configuration file class.
okay bestie, you're reading Simple(3) from the User Contributed Perl Documentation, and it's all about Config::Simple π
β¨ SYNOPSIS β¨
Here's the whole vibe in code, fr fr:
use Config::Simple;
# --- Simple usage. Loads the config. file into a hash:
Config::Simple->import_from('app.ini', \%Config);
# --- OO interface:
$cfg = new Config::Simple('app.ini');
# accessing values:
$user = $cfg->param('User');
# getting the values as a hash:
%Config = $cfg->vars();
# updating value with a string
$cfg->param('User', 'sherzodR');
# updating a value with an array:
$cfg->param('Users', ['sherzodR', 'geek', 'merlyn']);
# adding a new block to an ini-file:
$cfg->param(-block=>'last-access', -values=>{'time'=>time()});
# accessing a block of an ini-file;
$mysql = $cfg->param(-block=>'mysql');
# saving the changes back to file:
$cfg->save();
# --- tie() interface
tie %Config, "Config::Simple", 'app.ini';
πΈ ABSTRACT πΈ
okay so reading and writing configuration files is one of the most frequent tasks of any software design β not me pretending that's not true π. Config::Simple is the library that helps you with it.
Config::Simple is a class representing configuration file object. It supports several configuration file syntax and tries to identify the file syntax automatically. Library supports parsing, updating and creating configuration files. slay β¨
π¦ ABOUT CONFIGURATION FILES π¦
Keeping configurable variables in your program source code is ugly, really. And for people without much of a programming experience, configuring your programs is like performing black magic. Besides, if you need to access these values from within multiple files, want your programs to be able to update configuration files or want to provide a friendlier user interface for your configuration files, you just have to store them in an external file. That's where Config::Simple comes into play, making it very easy to read and write configuration files.
If you have never used configuration files before, here is a brief overview of various syntax to choose from. Otherwise you can jump to "PROGRAMMING STYLE". iykyk β¨
π SIMPLE CONFIGURATION FILE π
Simple syntax is what you need for most of your projects. These are, as the name asserts, the simplest. File consists of key/value pairs, delimited by nothing but white space. Keys (variables) should be strictly alpha-numeric with possible dashes (-). Values can hold any arbitrary text. Here is an example of such a configuration file:
Alias /exec
TempFile /usr/tmp
Comments start with a pound (#) sign and cannot share the same line with other configuration data. β οΈ
π HTTP-LIKE SYNTAX π
This format of separating key/value pairs is used by HTTP messages. Each key/value is separated by semi-colon (:). Keys are alphanumeric strings with possible -. Values can be any arbitrary text:
Example:
Alias: /exec
TempFile: /usr/tmp
It is OK to have spaces around :. Comments start with # and cannot share the same line with other configuration data. periodt π
π INI-FILE π
These configuration files are more native to Win32 systems. Data is organized in blocks. Each key/value pair is delimited with an equal (=) sign. Blocks are declared on their own lines enclosed in [ and ]:
[BLOCK1]
KEY1=VALUE1
KEY2=VALUE2
[BLOCK2]
KEY1=VALUE1
KEY2=VALUE2
Your Winamp 2.x play list is an example of such a configuration file. iconic π΅
This is the perfect choice if you need to organize your configuration file into categories:
[site]
url="http://www.handalak.com"
title="Web site of a \"Geek\""
author=sherzodr
[mysql]
dsn="dbi:mysql:db_name;host=handalak.com"
user=sherzodr
password=marley01
π§ SIMPLIFIED INI-FILE π§
These files are pretty much similar to traditional ini-files, except they don't have any block declarations. This style is handy if you do not want any categorization in your configuration file, but still want to use = delimited key/value pairs. While working with such files, Config::Simple assigns them to a default block, called default by default :-).
url = "http://www.handalak.com"
Comments can begin with either pound (#) or semi-colon (;). Each comment should reside on its own line π«Ά
β¨ PROGRAMMING STYLE β¨
Okay so bestie, listen π most programs literally just need to read settings out of a config file and dump them into a hash. That's it. That's the whole vibe. And if that's all you need, you can just call its import_from() class method with the name of the configuration file and a reference to an existing (possibly empty) hash:
Config::Simple->import_from('myconf.cfg', \%Config);
And boom π
your hash %Config now holds all the configuration file's key/value pairs. The keys of the hash are the variable names inside your configuration file, and the values are their respective values. And if "myconf.cfg" was a traditional ini-file, the keys of the hash consist of block name and variable delimited with a dot, like "block.var".
If that's all you need, you can stop right here, fr fr. Otherwise, read on bestie, because there is so much more Config::Simple offers π
πΈ READING THE CONFIGURATION FILE πΈ
To unlock the extra features of the library, you gotta use its object interface:
$cfg = new Config::Simple('app.cfg');
The line above reads and parses the configuration file accordingly. It tries to guess which syntax is used by passing the file to the guess_syntax() method. Or, alternatively, you can create an empty object and only then read the configuration file in:
$cfg = new Config::Simple();
$cfg->read('app.cfg');
Same as the first example, read() also calls guess_syntax() on the file π«Ά
Now, if for any reason it fails to guess the syntax correctly (which is, like, less likely ngl), you can try to debug by using its guess_syntax() method. It expects a file handle for a configuration file and returns the name of a syntax. The return value is one of "ini", "simple" or "http".
open(FH, "app.cfg");
printf("This file uses '%s' syntax\n", $cfg->guess_syntax(\*FH));
π¦ ACCESSING VALUES π¦
Once you've read the configuration file in successfully (slay), you can use the param() method to access the configuration values. For example:
$user = $cfg->param("User");
...will return the value of "User" from either a simple configuration file, or an http-styled configuration, as well as simplified ini-files β¨ To access the value from a traditional ini-file, consider the following syntax:
$user = $cfg->param("mysql.user");
The above returns the value of "user" from within the [mysql] block. Notice the use of the dot . to delimit block and key names π
Config::Simple also supports the vars() method, which, depending on the context used, returns all the values either as a hashref or a hash:
my %Config = $cfg->vars();
print "Username: $Config{User}";
# If it was a traditional ini-file:
print "Username: $Config{'mysql.user'}";
If you call vars() in scalar context, you'll end up with a reference to a hash:
my $Config = $cfg->vars();
print "Username: $Config->{User}";
And if you know what you're doing (main character energy only π), you also have the option of importing all the names from the configuration file into your current name space as global variables. All the block/key names will be uppercased and converted to Perl's valid variable names β that is, all the dots (the block-key separator) and other '\W' characters will be substituted with underscore '_':
$cfg = new Config::Simple('app.cfg');
$cfg->import_names();
# or, with a single line:
Config::Simple->new('app.cfg')->import_names();
print STDERR "Debugging mode is on" if $DEBUG_MODE;
So in the example above, if there was a variable 'mode' under the [debug] block, it's now accessible via $DEBUG_MODE, as opposed to $cfg->param('debug.mode') π
import_names() by default imports the values into its caller's name space. Optionally, you can specify where to import the values by passing the name of the name space as the first argument. It also prevents potential name collisions:
Config::Simple->new('app.cfg')->import_names('CFG');
print STDERR "Debugging mode is on" if $CFG::DEBUG_MODE;
But if all you want is to import values from a configuration file, the syntax above might still seem longer than necessary. That's exactly why Config::Simple supports the import_from() class method, which is called with the name of the configuration file. It'll call import_names() for you:
Config::Simple->import_from('app.cfg');
That line imports all the variables into the caller's name space. It's similar to calling import_names() on an object. If you pass a string as the second argument, it'll treat it as the alternative name space to import the names into. And as we already showed in the very first example, you can also pass a reference to an existing hash as the second argument β in that case, that hash will be modified with the values of the configuration file π
# import into $CFG name space:
Config::Simple->import_from('app.cfg', 'CFG');
# import into %Config hash:
Config::Simple->import_from('app.cfg', \%Config);
Both of those import all the values into the 'CFG' name space. And import_from() returns the underlying Config::Simple object (which, lowkey, you may not even need anymore):
$cfg = Config::Simple->import_from('app.cfg', \my %Config);
$cfg->write('app.cfg.bak');
π UPDATING THE VALUES π
Configuration values, once read into Config::Simple, can be updated from within your program by using the same param() method you used for accessing them. For example:
$cfg->param("User", "sherzodR");
That line changes the value of "User" to "sherzodR". Similar syntax applies to ini-files too:
$cfg->param("mysql.user", "sherzodR");
And if the key you're trying to update doesn't exist? It gets created, bestie β¨ For example, to add a new [session] block to your ini-file, assuming this block doesn't already exist:
$cfg->param("session.life", "+1M");
You can also delete values by calling the delete() method with the name of the variable:
$cfg->delete('mysql.user'); # deletes 'user' under [mysql] block
π SAVING/WRITING CONFIGURATION FILES π
Okay important thing: all those updates to the configuration values are in-memory operations. They do not reflect in the file itself π To modify the files accordingly, you need to call either the write() or save() methods on the object:
$cfg->write();
That writes the modifications to the configuration file. Alternatively, you can pass a name to either write() or save() to indicate the name of the file to create instead of modifying the existing configuration file:
$cfg->write("app.cfg.bak");
And if you want the changes saved at all times, you can turn autosave mode on by passing a true value to $cfg->autosave(). It makes sure that before your program is terminated, all the configuration values are written back to its file:
$cfg = new Config::Simple('aff.cfg');
$cfg->autosave(1);
π CREATING CONFIGURATION FILES π
Sometimes your programs might want to create their own configuration files on the fly, possibly from user input, and honestly? Iconic behavior. To create a configuration file from scratch using Config::Simple, simply create an empty configuration file object and define your syntax. You can do that by either passing the "syntax" option to new(), or by calling the syntax() method. Then play with the param() method as you normally would. When you're done, call the write() method with the name of the configuration file:
$cfg = new Config::Simple(syntax=>'ini');
# or you could also do:
# $cfg->autosave('ini')
$cfg->param("mysql.dsn", "DBI:mysql:db;host=handalak.com");
$cfg->param("mysql.user", "sherzodr");
$cfg->param("mysql.pass", 'marley01');
$cfg->param("site.title", 'sherzodR "The Geek"');
$cfg->write("new.cfg");
This creates a file "new.cfg" with the following content:
; Config::Simple 4.43
; Sat Mar 8 00:32:49 2003
[site]
title=sherzodR "The Geek"
[mysql]
pass=marley01
dsn=DBI:mysql:db;host=handalak.com
user=sherzodr
Neat, huh? π
The supported syntax keywords are "ini", "simple" or "http". Currently there's no support for creating simplified ini-files, just so you know.
π MULTIPLE VALUES π
Ever wanted to define an array of values inside your single configuration variable? I have! That's why Config::Simple supports this fancy feature too. Simply separate your values with a comma:
Files hp.cgi, template.html, styles.css
Now the param() method returns an array of values:
@files = $cfg->param("Files");
unlink $_ for @files;
And if you want a comma as part of a value, just enclose the value(s) in double quotes:
CVSFiles "hp.cgi,v", "template.html,v", "styles.css,v"
And in case you want any of the values to hold a literal quote ", you can escape it with a backslash:
SiteTitle "sherzod \"The Geek\""
π§ TIE INTERFACE π§
If OO style intimidates you, and import_from() is too simple for you (no shade, we love options), Config::Simple also supports the tie() interface. This interface lets you tie() an ordinary Perl hash to the configuration file. From that point on, you can use the variable as an ordinary Perl hash π¦
tie %Config, "Config::Simple", 'app.cfg';
# Using %Config as an ordinary hash
print "Username is '$Config{User}'\n";
$Config{User} = 'sherzodR';
The difference between this and import_from($file, \%Hash) is that all the changes you make to the hash after tie()ing it will also reflect in the configuration file object. And if autosave() was turned on, they'll also be written back to the file:
tie %Config, "Config::Simple", "app.cfg";
tied(%Config)->autosave(1);
To access the methods provided in OO syntax, you need to get the underlying Config::Simple object. You can do that with the tied() function:
tied(%Config)->write();
β οΈ WARNING: the tie interface is experimental and not well tested yet. Let me know if you encounter a problem π
β¨ MISCELLANEOUS β¨
π CASE SENSITIVITY π
Okay so by default, configuration file keys and values are case sensitive π
. Which means $cfg->param("User") and $cfg->param("user") are referring to two different values. No cap.
But it is possible to force Config::Simple to ignore cases all together by enabling the -lc switch while loading the library:
use Config::Simple ('-lc');
WARNING: If you callwrite()orsave(), while working on-lcmode, all the case information of the original file will be lost. So use it if you know what you're doing π.
πΈ USING QUOTES πΈ
Some people suggest that if values consist of none alpha-numeric strings, they should be enclosed in double quotes. Well, says them! π Although Config::Simple supports parsing such configuration files already, it doesn't follow this rule while writing them. If you really need it to generate such compatible configuration files, the -strict switch is what you need:
use Config::Simple '-strict';
Now, when you write the configuration data back to files, if values hold any none alpha-numeric strings, they will be quoted accordingly. All the double quotes that are part of the value will be escaped with a backslash β¨.
π¦ EXCEPTION HANDLING π¦
Config::Simple doesn't believe in dying that easily (unless you insult it using wrong syntax) π. It leaves the decision to the programmer implementing the library. You can use its error() - class method to access underlying error message. Methods that require you to check for their return values are read() and write(). If you pass filename to new(), you will need to check its return value as well. They return any true value indicating success, undef otherwise:
# following new() always returns true:
$cfg = new Config::Simple();
# read() can fail:
$cfg->read('app.cfg') or die $cfg->error();
# following new() can fail:
$cfg = new Config::Simple('app.cfg') or die Config::Simple->error();
# import_from() calls read(), so it can fail:
Config::Simple->import_from('app.cfg', \%Config) or die Config::Simple->error();
# write() may fail:
$cfg->write() or die $cfg->error();
# tie() may fail, since it calls new() with a filename
tie %Config, "Config::Simple", 'app.cfg' or die Config::Simple->error();
π METHODS π
π οΈ new()
- constructor. Optionally accepts several arguments. Returns Config::Simple object. Supported arguments are filename, syntax, autosave. If there is a single argument, will be treated as the name of the configuration file.
π autosave([$bool])
- turns 'autosave' mode on if passed true argument. Returns current autosave mode if used without arguments. In 'autosave' mode Config::Simple writes all the changes back to its file without you having to call
write()orsave().
π read()
- accepts name of the configuration file to parse. Before that, it tries to guess the syntax of the file by calling
guess_syntax()method. Then calls either ofparse_ini_file(),parse_cfg_file()orparse_http_file()accordingly. If the name of the file is provided to the constructor -new(), there is no need to callread().
ποΈ param([$name], [$value])
- used for accessing and updating configuration variables. If used with no arguments returns all the available names from the configuration file.
ποΈ delete($name)
- deletes a variable from a configuration file.
$namehas the same meaning and syntax as it does inparam($name).
π§Ό clear()
- clears all the data from the object. Calling
save()or turningautosave()on results in an empty configuration file as well.
π¦ vars()
- depending on the context used, returns all the values available in the configuration file either as a hash or a reference to a hash.
π·οΈ import_names([$NS])
- imports all the names from the configuration file to the caller's name space. Optional argument, if passed, will be treated as the name space variables to be imported into. All the names will be uppercased. Non-alphanumeric strings in the values will be underscored.
π₯ import_from($file, \%hash | $NS)
- class method. If the second argument is a reference to an existing hash, it will load all the configuration contents into that hash. If the second argument is a string, it will be treated as the name space variables should be imported into, just like
import_names()does.
π§© get_block($name)
is mostly used for accessing blocks in ini-styled configuration files. Returns a hashref of all the key/value pairs of a given block. Also supported by param() method with the help of -block option:
$hash = $cfg->get_block('Project');
# is the same as saying:
$hash = $cfg->param(-block=>'Project');
π§± set_block($name, $values)
used in assigning contents to a block in ini-styled configuration files. $name should be the name of a [block], and $values is assumed to be a hashref mapping key/value pairs. Also supported by param() method with the help of -block and -value (or -values) options:
$cfg->set_block('Project', {Count=>3, 'Multiple Column' => 20});
# is the same as:
$cfg->param(-block=>'Project', -value=>{Count=>3, 'Multiple Column' => 20});
Warning: all the contents of a block, if previously existed will be wiped out. If you want to set specific key/value pairs, use explicit method:
$cfg->param('Project.Count', 3);
π as_string()
- returns the configuration file as a chunk of text. It is the same text used by
write()andsave()to store the new configuration file back to file.
πΎ write()
- writes the configuration file into disk. Argument, if passed, will be treated as the name of the file configuration variables should be saved in.
πΎ save()
- same as
write().
π dump()
- for debugging only. Dumps the whole Config::Simple object using Data::Dumper. Argument, if passed, will be treated as the name of the file object should be dumped in. The second argument specifies amount of indentation as documented in Data::Dumper manual. Default indent size is 2.
π¨ error()
- returns the last error message from read/write or import_* operations.
π TODO π
- Support for lines with continuation character,
'\'. Currently its support is restricted and quite possibly buggy. - Retaining comments while writing the configuration files back and/or methods for manipulating comments. Everyone loves comments!
- Retain the order of the blocks and other variables in the configuration files.
π BUGS π
Submit bugs and possibly patches to Sherzod B. Ruzmetov <sherzodr@cpan.org>.
π CREDITS π
Michael Caldwell (mjc@mjcnet.com)β whitespace support,-lcswitch and for various bug fixesScott Weinstein (Scott.Weinstein@lazard.com)β bug fix inTIEHASHRuslan U. Zakirov <cubic@wr.miee.ru>β default name space suggestion and patchHirosi Tagutiβimport_names()andimport_from()idea.Vitaly Kushneriukβ for bug fixes and suggestions
Β©οΈ COPYRIGHT Β©οΈ
Copyright (C) 2002-2003 Sherzod B. Ruzmetov.- This software is free library. You can modify and/or distribute it under the same terms as Perl itself
π AUTHOR π
Sherzod B. Ruzmetov E<lt>sherzodr@cpan.orgE<gt>URI: http://author.handalak.com
π SEE ALSO π
Config::General, Config::Simple, Config::Tiny
mwah π this page is perl v5.42.2, dated 2023-11-29, and it's Simple(3) β bye bestie π«Άβ¨
π¦ where this page comes from
- alpine 3.24: perl-config-simple-doc 4.59-r4 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms