Perl -p is the sweetness

A handy trick for programming perl is the -p flag. This tells perl to surround your code with:

while (<>) {
     ...          # your script goes here
} continue {
     print or die "-p destination: $!\n";

If you have a file with state names and 2 character codes, like “DE:Delaware”, you could convert that into SQL insert statements by feeding it to a simple perl script like follows:

#!/usr/bin/perl -p -w
s/(.*):(.*)/INSERT INTO states (state_value,state_name) VALUES ('$1','$2');/

Related Posts:

This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

3 Responses to Perl -p is the sweetness

  1. blackfog says:

    Even a single-command line if you use -e rather than the buffer.

  2. Eric S Law says:

    One of my fav perl oneliners is to modify files in place like this:
    perl -i.old -pe ‘s/oldstring/newstring/g’ somefile.txt

    Updates the file and saves the old one with .old suffix.

    The newest flag I’ve learned is ‘-l’ which puts n on print lines for you

  3. Eric – so did they ever fix the bug with the command line parsing that forced you to ALWAYS to “perl -pi.bak -e” instead of mixing the p, i, and e as you ought to be able to do?