Perl Pie

Holy Pearl “How do I change “pelican” to “pecan” in all the files in a directory?”. “Dude, use Perl Pie”!

I’m pretty familiar with Perl, having used it on and off whenever there’s a string manipulation related job to be done. I like Perl despite all it’s faults. I like writing Perl (not so keen on reading it though 🙂 ). I’ve been using Perl one-liners where I probably should be using Shell scripts but I used to forget what the right flags are until I heard the term “Perl Pie”.

perl -p -i -e 's/before/after/g' your.files*

-e is for “execute” – It allows you to define Perl code to be executed by the compiler

-p is for “process” – It adds a loop around your -e code so that it is applied to each line of any specified files and the contents of $_ are printed out and errors are thrown if a file can’t be read. You can think of it like it adds this:

while (<>) {
  # your -e code goes here
} continue {
  print or die "Can't open blah: $!\n";
}

-i is for “In-place Editing” – Without it, no files will be changed. With it, Perl renames the input file and reads from this renamed version while writing to a new file with the original name. If -i is given a string argument, then that string is appended to the name of the original version of the file. for example, Sometimes it’s handy to use -i~ so Perl creates a backup file before making your changes. if -i has no arguments, the file names don’t change.

Leave a Reply