Search code examples
linuxperlrm

Fast directory clean-up with Perl


I have a need to clean-up directory with millions of log files on my webserver. And I've found this great article on how to do this. There is, however, a couple interesting things in that one-liner, which I am interested in.

Here's the Perl code I am interested in:

for(<*>){((stat)[9]<(unlink))}

Runned with perl -e 'code'.

So, here are my questions:

  1. the for(<*>) construction - I assume it iterates through the files in the current directory. But where does it store the iterator?
  2. the stat and unlink functions expect at least one argument, I assume... But where is it?
  3. why the result of calling (stat)[9] is compared to the result of calling (unlink)? And what does it results in?

Sorry, I am a no-perl-ish guy, thus I do not understand all those Perl abbreviations. That's why I am asking this question.

Thanks!


Solution

  • That one liner takes many shortcuts:

    1. The <*> is a special case of the diamond operator. You can't access an iterator object, like in other languages. Here, it calls the glob function. In list context it returns a list from all the results (which are either lines of a file, or, as in your case, contents of a diretory. The return value of that is passed to for which iterates over a list and aliases the values in $_. $_ is the "default variable" for many functions…
    2. Which brings us here. Many core functions default to $_ with no argument. So do unlink and stat.
    3. (stat)[9] means execute stat in list context and select the 10th result (indices start at zero, this is the modify time). (compare that to an array access like $foo[9]).