Posts

Showing posts from March, 2011

Search and replace by parsing nested clause across multilines using recursive regex

Let me start with the answer. The answer is:

perl -p -i -e 'undef $/;$re = qr/\((?:[^()]*|(??{$re}))*\)/;s/(create\s+table\s+.[a-z,A-Z,0-9,.]*\s*$re)\s*(?!SPARSIFY)/$1 SPARSIFY /gis' test/*
Now the question and story behind it: 
Transforming existing code can be bit tricky and less useful sometimes. But at other times it can literally save our jobs! Here is a typical scenario:

FuncName ("Hell brakes $heck if(blah (blah(blah(".
"blah(blah))blah)))", Heaven);

If the above function is called million times at different places and you want to change that crazy looking nested structure inside a function argument what will you do ? Ok, you can slurp the file to a scalar as in here:
http://www.modernperlbooks.com/mt/2009/08/a-one-line-slurp-in-perl-5.html. Then use the recursive regexp idiom:

$re = qr/\((?:[^()]*|(??{$re}))*\)/;
     $input_scalar =~ s/(Hell\s+brakes\s+.[a-z,A-Z,0-9|.]*\s+if\s*$re)\s*(?!HELLIFY)/$1 HELLIFY /gis;

The $re grabs everything in the ne…