Ricky Levi
Ricky Levi

Reputation: 7997

Perl how to parse INI files that contains variables?

An INI file can have variables inside it like:

[section1]
root=/path/to/dir
home=%(root)s/my_home_dir/

Now, the Perl library Config::IniFiles doesn't seems to parse it, it passes it as raw strings

my $result = tie %info, 'Config::IniFiles', ( -file => $ini_file );

In Python there's a similar package called ConfigParser.RawConfigParser - that won't convert the variables, but then you can use ConfigParser.ConfigParser and it will.

Is there something similar in Perl, or a fix to what I'm looking for ?

Upvotes: 0

Views: 728

Answers (1)

ikegami
ikegami

Reputation: 386321

If you can't find an existing parser for the config file format you are using, you could simply use

sub get_conf {
   my ($hash, $key) = @_;
   my $val = $hash{key};
   return undef if !defined($val);

   $val =~ s{%\(([^()]*)\)}{ get($hash, $1) // "" }eg;
   return $val;
}

my $home = get_conf(\%conf, 'home');

Upvotes: 1

Related Questions