I Used a Regex, Now I Have Two Problems…

So, I’m 16 posts in on this blog now. Every post, I’m getting fancy with code blocks and such. You know,

like this.

To make one of those, it takes a div, span, code, and pre tag, along with some custom CSS. You know how irritating that gets typing it over and over again? Did you guess “very”? You’d be right.

Luckily, I’m a programmer. I know regular expressions! I decided I’d try to remember how to do Perl. I wrote a script to handle regex find and replacing these tags. It can be found here.

I’ll not go over each line of that script, but here are some of the highlights:

On line 19:

if ($current =~ /^#/) { #comment found }

Checks to see if a line begins with a #. If it does, that line is a comment.

On line 23:

elsif ($current =~ /=/) { my @working = split(/=/, $current, 2); chomp($working[0]); chomp($working[1]); $return_value{$working[0]} = $working[1]; }

Checks to see if the current line contains an equals sign. If it does, it splits the current line, using the first equals sign as the delimeter. Thereby allowing replacement text to contain an equals sign. The two tokens then have leading and trailing whitespace trimmed before being added to the return_value hash.

On line 48:

for my $pair (keys(%config)) { $current =~ s/$pair/$config{$pair}/; }

Iterates through the token/replacement pair, replaces tokens in the current line.

The script takes a text file as an argument, reads a dmp_helper.rc file located in the same directory as the script, and prints the expanded text to STDOUT.

Given an input file containing:

I'm %j% a %p% %b%, nobody loves me... He's %j% a %p% %b%, %f% a %p% family! spare him his life %f% %t% monstrosity!

…and a dmp_helper.rc containing:

%j%=just %p%=poor %f%=from %t%=this %b%=boy

…this output is produced:

I'm just a poor boy, nobody loves me... He's just a poor boy, from a poor family! Spare him his life from this monstrosity!

Trackbacks / Pingbacks

  1. An Intro To Parsec | Doing My Programming... - April 24, 2014

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: