Perl to the Rescue

Technical

For the last 10 years (-ish), I've been primarily a ColdFusion developer. Mix in a bunch of PHP, a bit of Java. No Perl. I've maintained a bit of existing Perl code like a Bugzilla installation and random scripts, but I don't consider myself a Perl developer and it's not listed on my resume. If I weren't tougher than a kevlar gumdrop, it would scare me just a little.

That said, I know it's a useful, powerful, versatile language. About a month ago I needed a change so I took a new gig where I seem to be writing a lot of Perl scripts. It's everything I thought it was: useful, powerful, versatile and scary. What I forget is that it can be executed from the command line. Yesterday I was looking at a ~500 line file. I needed to massage the content of the that file into a single comma-delimited list. You see where this is going, right?

Perl to the rescue (I can honestly say that I never thought I'd say that):

perl -0 -pi.bak -e 's/\n/,/sg' myfile

Argument Description
-0 Read the entire file into a single string
-p Print the modified output
-i Copy the existing content of myfile into myfile.bak
-e Execute the following command


One command, lots of time saved. That's economy of effort.


UPDATE 2005.05.10

After using this command a few times, I decided that the regex was simply too limited. This is especially true when moving from Windows to Unix with the native CRLF differences. I've started using the following command which includes a more robust regular expression for this kind of conversion:

perl -0 -pi.bak -e 's/[\n\r]+/,/sg' myfile


UPDATE 2007.08.13

One of the great hazards (and I use that word with tongue firmly planted in cheek) of the multi-platform environment I now work in is the CRLF hairball.

I repurposed this line to handle the need for a CRLF conversion:

perl -0 -pi.bak -e 's/\r\n/\n/g' myfile

tags:
HowTo, perl

Search

Rob  Wilkerson