Sunday, March 10, 2013

For Substance

That righteous Substance McGravitas recently posted one way to handle messing with some text files. There are easier ways to go about it, and I am a helpful beer snob:

Sample file contents:

% cat pissoff.list 
fuck you
you fucking wanker
go fuck yourself

% cat wanker.list 
useless git
bloody hell

What Substance wants to do is take those input files and wrap them in some simple XML. PERL is perfect for this job. Here's a quickly whipped up program to do so:


if ($#ARGV < 0) {
    print STDERR "\nUsage: abuse [files...]\n\n";
    print STDERR "I know you came here for abuse,";
    print STDERR " but you still need files as arguments.\n";
    print STDERR "Output goes to STDOUT, you probably "
    print STDERR "want to redirect it somewhere\n\n";

print "<XML>\n";

foreach $file (@ARGV) {
    if (-r $file) {
 open(FILE, "$file");
 @lines = <FILE>;

 foreach $line (@lines) {
     print "<words>\n\t<data>$line</data>\n</words>\n";
    } else {
 print STDERR "Can't read $file -- skipped\n";

print "</XML>\n";

Save that as a file called something (in my case I saved it as "abuse" -- just 'cause). Make it executable:

%chmod 755 abuse

Now run it with our two files:

% ./abuse pissoff.list wanker.list 
 <data>fuck you</data>
 <data>you fucking wanker</data>
 <data>go fuck yourself</data>
 <data>useless git</data>
 <data>bloody hell</data>

To store the output in a file, simply redirect the output somewhere using standard shell redirection:

% ./abuse pissoff.list wanker.list > fuckyou.xml

It took me twice as long to write this post than it did to write the code. PERL is a damn handy thing to have around.


  1. Back in me Wall St. daze, some of our tech guys swore by PERL.

    1. I can see that -- it's especially good if you need to translate one chunk of random-format-data-version-x to new-random-data-format-y.

      I don't use it all that much these days, but it comes in super handy every once in a while.

      It helps that after 20 years of using it I couldn't forget it if I tried.


By commenting here you're legally bound to buy me lots of yummy beer.