Monday, November 5, 2007

The Advantage of Using Perl Like Sed or Awk

Hey There,

Mostly, in shell scripts, you won't want to call Perl to do any processing for you. If your script has gotten to the point of complexity that only Perl can do the job, you should probably be writing your script in Perl.

However, there are times when it makes sense to use it, if only for brevity's sake. Perl will, of course, impose a slightly heavier load on your system when you call it from the shell. But unless you've got a 3,000,000 line gutbuster of a script on your hands, you'll never notice the difference and the shell probably won't flag at all either.

One of the best ways to utilize Perl within a shell script is to mimic the functionality of Sed and/or Awk; insofar as they're used to perform simple find-and-replace procedures on a file.

The problem with Sed and/or Awk is that (and I know this is trifling) when you process a file with either, you've got to direct the output somewhere (possibly a temporary file) and then write that result back over the original file (possibly altering the original file's permissions, which would need to be reset. With Perl, you can avoid that last step and, possibly, make your script more readable.

For instance: From within a shell script, this is what you'd have to do with Sed to replace the first instance of "bob" with "joe" for all lines in your file (we're assuming it has permissions of 755 and your system umask of 022 will make the new file have 644 permissions when it gets created).

sed 's/bob/joe/' filename >>tmpfilename
cp tmpfilename filename
chmod 755 filename

It's a slightly different command in Awk, but the copy-back and chmod still need to be done manually. If you call Perl, it will take care of managing that copy-back for you (by doing an inline edit which is - technically - the same thing at the execution level), like this:

perl -p -i -e 's/bob/joe/' filename

That's it. No worries about writing out to a temporary file and copying back. Now you don't have to worry about that and, as an added bonus, it looks a lot neater.

Simple as pie :)

, Mike