Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding a find2perl result

Tags:

find

perl

I have been working on a script that will recursive search a filesystem and delete any file (no directories) that is older than 20 days. I used the find2perl command (that is part of File::Find) and this was the result. (I noted that it didn't understand the -delete option, so I had to use the old -exec... option instead.)

(parts of the script truncated)

sub delete_old_files {
    my ($dev,$ino,$mode,$nlink,$uid,$gid);

    (($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
    -f _ &&
    (int(-M _) > 20) &&
    unlink($_);
}

I understand the lstat part, the -f file check, and the unlink, but I'm not sure how the (int(-M _) > 20) works. Obviously it is checking for modified date within 20 days, but I've never seen that syntax before, and curious to understand where it comes from and how it works. I'm also curious how it can reference the iterator as a plain underscore without using $_ for the -f and the time check piece.

like image 591
Tim S. Avatar asked Jan 04 '23 02:01

Tim S.


2 Answers

The results of the lstat call are cached. By using _, you avoid multiple lstat calls.

Does the same thing as the stat function (including setting the special _ filehandle) but stats a symbolic link instead of the file the symbolic link points to ... (emphasis mine)

From stat:

If stat is passed the special filehandle consisting of an underline, no stat is done, but the current contents of the stat structure from the last stat, lstat, or filetest are returned.

like image 145
Sinan Ünür Avatar answered Jan 14 '23 13:01

Sinan Ünür


From the docs for the -X functions:

-M Script start time minus file modification time, in days.

The special filehandle _ caches the last file stats, so any subsequent use of the -X _ will use the cached values.

like image 41
jm666 Avatar answered Jan 14 '23 11:01

jm666