http://www.perlmonks.org?node_id=516044

carcassonne has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

I'd like to add a second (and possibly others) values to a section of a configuration file. This is known as a multi-part value in Config::Std documentation. The problem is, when the config file is read, there's already one such multi-part value although for the moment it's the only one.

Like this:

[MYSECTION] element: test1
That config file is read and test2 should be added to give the following:

[MYSECTION] element: test1 element: test2

Problem is, when first read, Config::Std returns 'test1' as a scalar. How is it possible to add another value to a scalar unless a modification of the data type is made (i.e. erasing directly the scalar in memory and replacing it by an array) ? Or am I missing something about Config::Std (or Perl in general ;-) that would do this without directly hacking Config::Std's way of representing data ?

...Or when there's only one value, the 'element:' tag should be dropped...

Test code

Save the first snippet above in test.cfg and use the following:

use Config::Std; read_config 'test.cfg' => my %config; print $config{"MYSECTION"}{"element"} . "\n";

Replies are listed 'Best First'.
Re: Config::Std multi-part problem
by TheDamian (Vicar) on Dec 13, 2005 at 21:49 UTC
    If you want to convert a single-valued entry into a multi-valued entry, you need to convert the scalar to an array . Like so:
    use Config::Std; read_config 'test.cfg' => my %config; print $config{"MYSECTION"}{"element"} . "\n"; $config{"MYSECTION"}{"element"} = [ $config{"MYSECTION"}{"element"}, "test2", ]; write_config %config;
    Damian
      Thanks, this works fine.

      I now also use Contextual::Return to see if the value is a scalar in the first place:

      print "This is a scalar\n" if (SCALAR { $config{"MYSECTION"}{"element"} });

      If I had the time, I could look into Contextual::Return to see what code is SCALAR, and extract only that, but I see no problem so far in including the whole module.

      I've noticed a blank entry in %config. Please see the new thread I created for that subject.

Re: Config::Std multi-part problem
by bibliophile (Prior) on Dec 13, 2005 at 15:36 UTC
    For what it's worth, I'd recommend switching to XML::Simple unless you need to access existing INI-type files. I've found it to be much more powerful; it allows you to structure your config data to suit your needs (eg: repeated elements, multi-level nesting, and so on).

    -- WARNING: You are logged into reality as root.
      I do not access existing INI-type files, but I do access INI-type users ! ;-))

      For a more complex configuration file module, there's Config::Standard which offers a lot of options, in XML style.

        Correction: That's 'Config::General' instead of 'Config:Std'