in reply to Pattern Matching - a Tricky one
I don't recommend this solution because it uses string eval, it changes the order of the output data (and a little bit of the format), it reads the entire input file to do its work, and I wrote it without the aid of my usual morning chemicals. I'm not proud. The TIMTOWTDI made me do it.
On the plus side, it doesn't do anything so perverse as try to parse a nested data structure with regular expressions, and it uses recursion, if you're into that sort of thing.
# slurp! my $wholefile = join q{}, <DATA>; # It's a HoH, I swear! $wholefile = "\n$wholefile"; $wholefile =~ s{\n(\s*)(\S+)\s*=\s*}{\n$1'$2' =>}g; $wholefile = "{ $wholefile }"; # DANGER, Will Robinson! my $d = eval $wholefile; die $@ if $@; # Not exactly regular expressions $d->{'bakjob1_details'}{'debit'}{'customer2'} = 123456; $d->{'bakjob1_details'}{'credit'}{'customer2'} = 123456; $d->{'bakjob2_details'}{'debit'}{'customer2'} = 7337.64; $d->{'bakjob2_details'}{'credit'}{'customer2'} = 7337.64; output( $d, 2 ); sub output { my ( $href, $indent ) = @_; foreach my $key ( keys %{ $href } ) { my $value = $href->{$key}; my $in = q{ } x $indent; if ( ref $value eq ref {} ) { print "$in$key = {\n"; output( $value, $indent + 2 ); print "$in},\n"; } else { print "$in$key = $value,\n"; } } return; } __DATA__ bakjob1_details = { credit = { customer1= 2000.0, # I added a comma customer2 = -1500.0, customer3 = 0.0, }, debit = { customer1= 50000.0, customer2 = -2000.0, customer3 = 0.0, } }, bakjob2_details = { credit = { customer1= 1000.0, customer2 = 200.0, customer3 = 500.0, }, debit = { customer1= 600.0, customer2 = 659.0, customer3 = 887.0, } }
Output:
bakjob1_details = { debit = { customer1 = 50000, customer3 = 0, customer2 = 123456, }, credit = { customer1 = 2000, customer3 = 0, customer2 = 123456, }, }, bakjob2_details = { debit = { customer1 = 600, customer3 = 887, customer2 = 7337.64, }, credit = { customer1 = 1000, customer3 = 500, customer2 = 7337.64, }, },
|
|---|