What is the best way to parse INI file in Perl and convert it to hash?
Join Stack Overflow to learn, share knowledge, and build your career.
|
|
I prefer to use Config::IniFiles module. |
|||||
|
|
reading and write function for ini file edit:
sample usage: read conf file and saved to hash
change the your config attribute or added new config attributes edit
added new config
saved your new configuration to file
|
|||||||||
|
|
Try this module from CPAN: Config::INI::Reader |
||||
|
|
|
Config::Tiny is very easy and straightforward to use.
|
||||
|
|
|
Nitpicking on the above: Tie::Cfg, as downloaded from CPAN, does not handle sections and keys that may have spaces in them. It needs to be changed by adding quotes (") around the "keys" when setting the hash entries for both the section and the keys within the sections. The files I'm trying to read were generated by MS Windows' folks, and thus have plenty of spaces to go around. Config::Tiny, Config::IniFiles are fussy about the format. If any line is not of the form [section] or key=val, they throw an error and one can't get to the hashes, which, at least in Config::Files, are filled in properly anyway. It would be nice to have an ignore error option. The files I'm trying to read have some spurious M4 lines in it, that I could run through m4 to get rid of, but that is not necessary in what I'm trying to do with this particular script. |
|||
|
|
|
The best way is to make use of available modules in CPAN as what others have suggested. Below is just for your own understanding, let's say you have ini file like this:
you can do your own parsing w/o modules by using just Perl's regex (or string methods) + data structures like hashes. Sample Code:
output
|
|||||||||
|
|
If you like more perlish style then try
|
|||||
|