Sunday, August 12, 2007

Why Perl can be better than shell even for simple things

So Ben (formerly referred to as "the IT Guy") was talking about how in some cases a Bash script can be better than a Perl script. And he cited a specific example:

find /backup -mtime +7 -exec rm -f {} \;

Here's the rub... Try running the command against a directory with 25,000 files that need to be removed. It will take **hours** because of the continuous forking and spawning of /bin/rm.

Rewrite that with a Perl one-liner, and the same command will take **seconds**

perl -e 'use File::Find; find(sub{$a = lstat($_) && int(-M _) > 7 && unlink $_}, "/backup");'

One line. About as obscure as the previous approach. Sure that took me thirty seconds to write instead of ten, but on a big directory I'll be done long before the guy with the bash script.

In the interest of full disclosure, I really just stole the above example from perldoc File::Find, but I could have just as easily written it myself in a couple of minutes