Thursday, June 4, 2009

Perl to the Rescue

So here's a simple example of the sort of small Perl script I routinely cobble together for work. In this case I needed to run a quick external program repeatedly on a series of files and extract the parameters used inside. The files were named with whether or not they were correct, and this code uses that to build a table which sorts the files and summarizes the parameters.

There are a few ways this script is atypical for me. The brainwashing has worked -- for the first time I can remember, I actually started a script with use strict. I don't think it saved me this time, but it was simple enough to obey its strictures.

This is the first time I've used the DirHandle module. Combined with grep, it proved an elegant way to get the filenames to work on.

And actually, the use of grep to filter lists is a fairly new technique, which I think I picked up in my Perl 6 experiments.

By the way, once the full table was generated, I had the bug's cause pinned down in about twenty seconds.

1 comment:

  1. It would better to use lexical handles and 3+ arg open like

    open my $DATA, "-|", "code.exe", "$directory\\$file" or die "Unable to run code.exe: $!\n";

    The bareword handles are package globals, it would be easy to end up clobbering them in a different part of the program.

    The reasons for using the 3+ arg open is similar to using system(LIST) instead of system(STR) which is covered in perldoc -f system.

    Text::Reform or Perl6::Form would be a better than using format for reasons similar to the bareword handles and also because it lets you store your formats in variables and reuse them with multiple handles.