in reply to Pattern Matching - a Tricky one
My idea for your problem looks like this:
#!/usr/bin/perl use strict; use warnings; my $datafile = 'account.data'; my $searched_customer = 'customer2'; # modifications of values my %modify = ( credit => -100, debit => 250, ); my %indent = ( bakjob => ' 'x2, type => ' 'x4, customer => ' 'x6, ); # my %re = ( bakjob => qr{^$indent{bakjob}bakjob(\d+)_details}, type => qr{^ (debit|credit) =}, ); #open my $fh, '<', $datafile or die $!; my $fh = *DATA; # don't start before this line my $line_num = 4; while ( my $line = <$fh> ) { # only parse complete bakjob blocks after line $line_num if ( $. > $line_num && $line =~ m/$re{bakjob}/ .. $line =~ m/^$indent{bakjob}},?/ ) { # parse internal structure if ( $line =~ m/$re{type}/ ) { print $line; parse( $fh, $1 ); } else { print $line; } } # maybe this is wanted, if you need to get all lines printed: # if ( $. < $line_num ) { # print $line; # elsif ( $line =~ m/$re{bakjob}/ .. $line =~ m/^$indent{bakjob}}, +?/ ) { # # parse internal structure # .... # } # else { # print $line; # } } sub parse { my ( $fh, $type ) = @_; while ( my $line = <$fh> ) { chomp $line; my ( $customer, $value ) = split m{\s*=\s*|,}, $line; $customer =~ s/^\s+//; if ( $customer eq $searched_customer ) { printf "$indent{customer}%s = %.1f\n", $customer, $value+$ +modify{$type}; } else { print $line, "\n"; } last if $line =~ m/^$indent{type}},?/; } } __DATA__ bakjob1_details = { credit = { customer1= 2000.0, 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, } }
updates:
|
|---|