Main Content

Dont bother to write a Perl program

Archive - Originally posted on "The Horse's Mouth" - 2008-10-10 05:53:13 - Graham Ellis

I can - very easily - write a Perl program to process every line of an incoming data file - indeed, that's much of where Perl originated as the "Practical Extraction and Reporting Language"

Here's a short example that processes every line of a file and reports each line that includes the string PHP as the second field of our line (which in the example happens to be a person's top skill):

open (FH,"../../requests.xyz") or die;
while ($line = <FH>) {
 chop ($line);
 @F = split (/\s+/,$line) ;
 if ($F[1] eq "PHP") {
  print $line;
  print "\n";
 }
}


Quick and easy, for sure ... but not as short (nor as quick and easy) as it might be for someone who's written a lot of Perl - this one line does the same:

perl -pae '$F[1] eq "PHP" or $_ = ""' ../../requests.xyz

Perhaps this is so short as to be obscure? If you're working in an environment when you often have to filter out a file quickly, then it's an excellent approach. If you're doing a lot of shell scripting, then a few Perl one-liners like this can save you an awful lot of more complex looking awks and seds.

As Damien Conway (one of the Perl team) said when I heard him lecture: "We're giving you a lot of very powerful tools. Be careful how you use them".