There are many nice things about Perl. But what I like best are one-liner scripts. I think nothing beats Perl when it comes to this feature.
1. A quick way of counting lines of code in your project:
$ find myproject -type f -name “*.java” | xargs perl -ne ‘print if !/^\s*$/’ | wc -l
You’ll notice that this also counts comment lines. For me, I also want to count lines of comments because they’re also work done.
2. Sometime ago, a friend asked me how to display a date two days earlier. She needed this in a shell script so the output has got to be STDOUT and can be invoked like a shell command.
Thu May 8 13:20:04 PDT 2008
$ TWO_DAYS_AGO=`perl -e ‘print scalar localtime(time() – 86400 * 2);’`
$ echo $TWO_DAYS_AGO
Tue May 6 13:20:10 2008
One can definitely write this in other languages, but I’m sure it would take more that one line of code. In addition, it would also require creating a separate script file, thus, it’s one more file to manage and maintain. While this way, it can be directly embedded in her shell script.
The key to this one-liner scripts is the -n and -e options in Perl. The -e option gives the ability to execute Perl commands inline. The -n option gives the ability to iterate over each line in STDIN. This is similar to AWK and SED but with the power of a full blown programming language.