Nice things about Perl

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.

$ date
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.

Advertisements

2 thoughts on “Nice things about Perl

  1. howdy there, i just saw your web portal listed on bing, and i must say that you express interestingly well via your blog. i am very impressed by the way that you compose, and the message is outstanding. in any case, i would also love to know whether you would love to exchange links with my web portal? i will be more than happy to reciprocate and drop your link on in the link exchange area. waiting for your response, thanks and enjoy your day!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s