in reply to How do I set up the recursion?
Seems to me that the biggest problem here is that you've written a P::RD grammer, which parses the Config file and produces a data structure to represent it. You then need to hand-roll your own parser to parse the output from P::RD in order to parse that into the format that you really want.
I realise that this isn't your fault. I spent some time reading the P::RD docs trying to work out how to get it to produce the format you want directly and save the second level of parsing. Whilst it may be possible, I gave up trying after many false starts and no apparent way to control the output format of P::RD.
This probably isn't what you want, but here's my take on the original problem of parsing this type of file. It use regexes and produces the required output in a single pass. No guarentees that it's complete or bullet proof, but I found this easier (by far) working out how to intervene in the P::RD process.
# perl -slw use strict; use re 'eval'; use Data::Dumper; use vars qw[%Config]; # A global hash to contain the data my $re_pair = qr{ # key=value [[#;]comment text\n] (?{ our ($key, $value, $comment)=() }) # local vars (\w+) (?{ $key = $^N }) # Capture & save the keyname = (\w+) (?{ $value = $^N }) # Capture & save the value (?: \s+ # obligatory whitespace [#;] # oblig. comment card - either or ([^\n]+) (?{ $comment = $^N }) # Capture & save the comment \n )? # zero or one \s* # If we got here, we have key/name comment?, so save them (?{ $Config{$section}{$key} = [ $value, $comment ] }) }x; my $re_section = qr{ # consist of [label] pairs* (?{ our ($section)=undef }) # Init the section labe +l [[] ([^]]+) []] # Capture the label # Save it. Create a key to hold the pairs (?{ $section = $^N; $Config{$section} = undef }) # zero or more pair sounded by optional while space. \s* $re_pair* \s* }x; my $re_file = qr{ # A file consists of 1 or more sections $re_section+ }x; my $data = do{ local $/; <DATA> } . $/; # slurp the file $data =~ m[$re_file]; # parse it print Dumper \%Config; # Use it __DATA__ [Section1] key1=value1 key2=value2 #comment key3=value3 [Section2] key4=value4 key5=value5 ;Comment2 [Section3]
Output
$VAR1 = { 'Section1' => { 'key2' => [ 'value2', 'comment' ], 'key1' => [ 'value1', undef ], 'key3' => [ 'value3', undef ] }, 'Section3' => undef, 'Section2' => { 'key5' => [ 'value5', 'Comment2' ], 'key4' => [ 'value4', undef ] } };
|
|---|