in reply to Contextual find and replace large config file
Here's a version that uses a HoH to allow multiple changes to multiple contexts in one pass.
#!/usr/bin/perl # https://perlmonks.org/?node_id=1227916 use strict; use warnings; $SIG{__WARN__} = sub {die @_}; ##################### configuration section my %changes = ( ObjectType1 => { Param1 => 0, Param2 => 'SomeOtherText' }, ObjectType4 => { Param3 => 'Replacement' }, Foo => { Param2 => 'FooChanged' }, ); ##################### end configuration section my $allcontexts = join '|', sort keys %changes; my $contextpattern = qr/\b($allcontexts)\b/; my %patterns; for my $section (keys %changes) { my $all = join '|', keys %{ $changes{$section} }; $patterns{$section} =qr/\b($all)\b/; } local $/ = "\n}\n"; while( <DATA> ) { if( /$contextpattern/ ) { my @context; print $& while @context && $patterns{$context[-1]} && /\G(\h*$patterns{$context[-1]} = ).*\n/gc ? "$1$changes{$context[-1]}{$2}\n" =~ /.*/s : @context && /\G\h*\}\n/gc ? pop @context : /\G\h*([\w ]+)\n\h*\{\n/gc ? push @context, $1 : /\G.*\n/gc; } else { print; } } __DATA__ ObjectType1 { Param1 = 8 NestedObject { Param1 = 3 Param2 = SomeText } Param2 = SomeText } ObjectType2 { Foo { Param1 = StaySame Param2 = FooChange ObjectType4 { Param1 = DoNotReplaceThis Param3 = ReplaceThis } } } ObjectType1 { Param1 = ReplaceThis Param3 = DoNotReplaceThis Foo { Param1 = StaySame ObjectType4 { Param1 = DoNotReplaceThis Param3 = ReplaceThis } } }
|
---|