EchoAngel has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I have this cgi script. I am dreaming of : everytime the user visits the cgi script, the script would automatically delete any files in my temp directory that are 24 hours or any hours difference from the current time the cgi script is used. Any simple ideas on how to do this? packages?
  • Comment on Easy way to Remove Files if match condition time?

Replies are listed 'Best First'.
Re: Easy way to Remove Files if match condition time?
by friedo (Prior) on Feb 04, 2005 at 21:32 UTC
    Get the current time with time.
    Get a list of the files in your temp directory with glob or opendir.
    Get the creation time of each file with stat.
    See if the difference between now and the ctime is greater than (60 * 60 * 24 ).
    If it is, delete the file with unlink.
      Get the creation time of each file with stat.
      See if the difference between now and the ctime is greater than (60 * 60 * 24 ).
      Ahem, ctime is the inode modification time, not the creation time. UNIX at least, doesn't record that information.

      Dave.

        You're right, but as these were described as temp files it's probably safe to bet that they were created once and not modified after. I should have been more clear about that though.
Re: Easy way to Remove Files if match condition time?
by jpk236 (Monk) on Feb 04, 2005 at 21:43 UTC
    To emphasize on the use of stat. You could get the epoch of the creation time of the file by doing:
    #>stat -s FILE | awk '{print $11}' | sed "/.*=/s///"
    that was my first attempt at sed, be gentle. You get the idea though.

    or in perl:
    if (-M FILE > 1) { unlink FILE; }
    Where 1 == one 24 hour day. If you wanted 12 hours -- it would be 0.5. Have Fun.

    Justin
      thank you so much!!