The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Config::Natural - Module that can read easy-to-use configuration files

SYNOPSIS

Lets say you have a file mail.conf

    name = John Doe
    email = jdoe@somewhere.net
    server = mail.somewhere.net
    signature = -
John Doe
--
Visit my homepage at http://www.somewhere.net/~jdoe/
.

You can read it using the following program:

    use Config::Natural;
    my $mailconf = new Config::Natural 'mail.conf';

and you can for example print the signature:

    print $mailconf->param('signature');

DESCRIPTION

This module has been written in order to provide an easy way to read simple configuration files. The syntax of these configuration files is what seemed to me the most natural way to write these files, hence the name of this module.

One of the reason I wrote this module is that I wanted a very easy way to feed data to HTML::Template based scripts. Therefore the API of Config::Natural is compatible with HTML::Template, and you can write programs as simple as:

    use strict;
    use Config::Natural;
    use HTML::Template;
    
    my $source = new Config::Natural 'file.src';
    my $tmpl = new HTML::Template type => 'filename', 
            source => 'file.tmpl', associate => $source;
    print $tmpl->output;

And this is not just another trivial example: I use scripts nearly as simple as this one to create most of my pages.

SYNTAX

Affectations

To affect a value to a parameter, simply write:

    greetings = hello world

The parameter greetings will have the value "hello world". You can also give multi-lines values this way:

    text = -
    Perl is a language optimized for scanning arbitrary text files, 
    extracting information from those text files, and printing 
    reports based on that information.  It's also a good language 
    for many system management tasks.  The language is intended to 
    be practical (easy to use, efficient, complete) rather than 
    beautiful (tiny, elegant, minimal).
    
    [from perl(1)]
    .

Think of this as a "Unix inspired" syntax. Instead of giving the value, you write "-" to mean "the value will follow" (in Unix, this means the data will come from standard input). To end the multi-lines value, you simply put a single dot "." on a line (as in Unix mail, but it needn't be on the first column).

Lists

If you need to write several identical records, you can use lists. The syntax is:

    list_name {
        parameter = value
        text = -
        This text may be as long as you wish. 
        .
    }

Example: a version history

    ## that's the version history of Config::Natural :)
    
    history {
        date = 2000.10.10
        version = 0.7.0
        comment = First fully functional release as an independent module.
    }
    
    history {
        date = 2000.11.04
        version = 0.7.1
        comment = Minor change in the internal structure: options are now grouped.
    }
    
    history {
        date = 2000.11.05
        version = 0.8.0
        comment = Code cleanup (mainly auto-generation of the options accessors).
        comment = Added list support.
    }

Lists can be nested. Example:

    machine {
        name = neutron
        sys = linux
        
        service {
            type = firewall
            importance = critical
       }
    }

    machine {
        name = proton
        sys = linux
        
        service {
            type = proxy
            importance = low
       }
        
        service {
            type = router
            importance = medium
       }
    }

As a shorthand, you can write something like

    flavour = lemon
    flavour = strawberry
    flavour = vanilla

instead of

    flavours {
        flavour = lemon
    }

    flavours {
        flavour = strawberry
    }

    flavours {
        flavour = vanilla
    }

As you see, Config::Natural automatically creates a surrounding list around the parameter "flavour", and names this list using the plural of the list name, i.e. "flavours" (ok, I'm only appending a "s" for now ;)

Such a construct can be also be nested.

Note: There must be only one item on each line. This means you can't write:

    line { param = value }

but instead

    line {
      param = value
    }

I don't think it's a big deal, because the aim of Config::Natural is to be fast and read files with a clear and simple syntax.

Inclusion

You can include a file using the "include" keyword. For example:

    # including some other file
    include generic.conf
    
    # now do specific stuff
    debug = 0
    fast = 1

If the argument is the name of a directory, all the files inside that directory are included. Check read_source() for more information.

Comments

You can use comments in your file. If a line begins with a sharp sign "#", it will be ignored. The sharp sign needs not being in the first column though.

OBJECTS OPTIONS

Syntax Options

If the default symbols used in the configuration file syntax doesn't fit your needs, you can change them using the following methods. Of course you must call these before reading the data file(s).

affectation_symbol

Use this accessor to change the affectation symbol. Default is "=".

multiline_begin_symbol

Use this accessor to change the multiline begin symbol. Default is "-".

multiline_end_symbol

Use this accessor to change the multiline end symbol. Default is ".".

comment_line_symbol

Use this accessor to change the comment symbol. Default is "#".

list_begin_symbol

Use this accessor to change the list begin symbol. Default is "{".

list_end_symbol

Use this accessor to change the list end symbol. Default is "}".

include_symbol

Use this accessor to change the include symbol. Default is "include".

Other Options

case_sensitive

Use this accessor to change the case behaviour. Default is 1 (case sensitive).

auto_create_surrounding_list

Use this accessor to enable or disable the auto creation of surrounding lists. Default is 1 (enabled).

read_hidden_files

Use this accessor to allow of forbid Config::Natural to read hidden files when reading a directory. Default is 0 (don't read hidden files).

METHODS

new ( )

This method creates a new object. You can give an optional parameter, in which case the read_source() method is called with that parameter.

read_source ( FILENAME )
read_source ( FILEHANDLE )

This method reads the content of the given file and returns an object that contains the data present in that file. The argument can be either a file name or a file handle. This is useful if you want to store your parameters in your program:

    use Config::Natural;
    my $conf = new Config::Natural \*DATA;
    
    $conf->param(-debug => 1);  ## set debug on
    
    if($conf->param('debug')) {
        print "current options:\n";
        print $conf->dump_param(-prefix => '  ');
    }
    
    # ...
    
    __END__
    ## default values
    verbose = 1
    debug = 0
    die_on_errors = 0

If the argument is a directory name, read_source() then recursively reads all the files present in that directory. Invisible files (dot-files) are read only when the option read_hidden_files is enabled.

You can call the read_source() method several times if you want to merge the settings from different configuration files.

param ( )
param ( LIST )
param ( HASHREF )

This is the general purpose manipulating method. It can used to get or set the value of the parameters of an object.

1) Return the list of the parameters:

    @params = $conf->param;

2) Return the value of a parameter:

    print $conf->param('debug');

3) Return the values of a number of parameters:

    @dbg = $conf->param(qw(debug verbose));

4) Set the value of a parameter:

    ## using CGI.pm-like syntax
    $conf->param(-debug => 0);
    
    ## using a hashref
    $conf->param({ debug => 0 });

5) Set the values of a number of parameters

    ## using Perl/Tk-like syntax
    $conf->param(
        -warn_non_existant => 1, 
        -mangle => 0 
    );
    
    ## using a hashref
    $conf->param(
      { 
        warn_non_existant => 1, 
        mangle => 0 
      }
    );
all_parameters ( )

This method returns the list of the parameters of an object.

delete ( LIST )

This method deletes the given parameters.

delete_all ( )

This method deletes all the parameters.

clear ( LIST )

This method sets the given parameters to undef.

clear_params ( )

This method sets all the parameters to undef.

dump_param ( OPTIONS )

This method returns a dump of the parameters as a string using the current format of the Config::Natural object. It can be used to simply print them out, or to save them to a configuration file which can be re-read by another Config::Natural object.

Options

  • nospace - If you set this option to true, no space will be printed around the affectation symbol.

  • prefix - If you set this option to a string, it will be printed before printing each parameter.

  • suffix - If you set this option to a string, it will be printed after printing each parameter.

write_source ( )
write_source ( FILENAME [, OPTIONS] )
write_source ( FILEHANDLE [, OPTIONS] )

This method writes the current object to the given file name or file handle. Remaining parameters, if any, will be passed unmodified to dump_param(). If no argument is given, the file or handle used by the last call of read_source() will be used.

set_handler ( PARAM, CODEREF )

This method can be used to hook a handler to a particular parameter. The subroutine code will receive the name of the parameter and the value being affected as arguments. The return value of the code will be used as the actual value. An example function could look like this:

    sub crypt_handler {
        my $param = shift;
        my $value = shift;
        return crypt($value, $param);
    }
    
    $conf->set_handler('passwd', \&crypt_handler);
delete_handler ( PARAM )

This method can be used to remove the handler of a parameter.

has_handler ( PARAM )

This method checks whether a parameter has a handler or not.

AUTHOR

Sébastien Aperghis-Tramoni <sebastien@aperghis.net>

COPYRIGHT

Config::Natural is Copyright (C)2000-2003 Sébastien Aperghis-Tramoni.

This program is free software. You can redistribute it and/or modify it under the same terms as Perl itself.