Peeter Joot's (OLD) Blog.

Math, physics, perl, and programming obscurity.

A fun regular expression for the day. change all function calls to another.

Posted by peeterjoot on December 18, 2009

Hit some nasty old school code today that dates back to our one-time 16-bit OS/2 port. I figured out that 730 lines of code for an ancient function called sqlepost() could all be removed if I could make a change of all lines like so:


(83 places). A desirable side effect of making this change is that we will stop logging the return code as a byte reversed hex number, and instead log it as a return code. Easier on developers and system testers alike.

perl -p is once again a good friend for this sort of task

\s*(.*?)\s*, # componentID -- unused.
\s*(.*?)\s*, # functionID
\s*(.*?)\s*, # probe
\s*(.*?)\s*, # index -- unused.
\s*(.*?)\s*, # size -- unused.
\s*&(.*?)\s*\)\s*; # rc
/pdLog( PD_DEV, $2, $6, $3, PD_LEVEL_SEV, 0 ) ;/x ;

I made a quick manual modification of each of the call sites that weren’t all in one line, with control-J in vim to put the whole function call on one line, then just had to run:

perl -p -i ./replacementScript `cat listOfFilesWithTheseCalls`

Voila! Very nice if I have to say so myself;)

EDIT: it was pointed out to me that the regular expressions used above are not entirely obvious.  Here’s a quick synopsis:

\s       space
.        any character
*        zero or more of the preceding
(.*)     capture an expression (creates $1, $2, ...)
            ie. zero or more of anything.
(.*?)    capture an expression, but don't be greedy, only capturing the
            minimal amount.
\(       a plain old start brace character (ie. non-capturing)
\)       a plain old end brace character.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: