Science Gateway > Protocols > Cell Biology Protocols - Table of Contents
Star Republic: Guide for Biologists

Perl Example 6 --- archive old files

The following script checks a folder for old files and then moves the old files to a new folder.

User need to input the name of the folder to be checked (dir1), the age of file considered to be old (days), and the archive directory name (dir2), i.e., to run in MS-DOS, use the following command:

perl myfile.pl dir1 dir2 days

#!perl
# This program check files in a directory for "date of last modified".
# If the files are older than the user provided time, it will be moved to a different folder.


#input name of the data directory from command line 
$dir = @ARGV[0]; 

#input name of the output directory
$outdir = @ARGV[1];

#input number of days, greater than which a file will be considered old, default is 30
$days = @ARGV[2];
$days = 30 if($days eq 0);

#remind user there is no input data directory or column number
if(!$dir or !$outdir ) {
  print "No input or output directory  names.\nUsage: perl my_perl.pl dir1 dir2 no_days\n";
}

#read the directory 
opendir(DIR, $dir) or die "can not open directory $dir\n";

 while($name = readdir(DIR)) {
   #save data file names in an array, don't include . and .. 
   push(@files, $name) if( !($name eq '.' || $name eq '..') );
 }

closedir(DIR) or  die "can not close directory $dir\n";

#process data
if( $outdir ) {
  
  #check files, if old copy to new directory
  for($i=0; $i < @files; $i++) {
    $infile = $dir.'/'.@files[$i]; 
   
    open(IN, "$infile") or die "can't open $infile: $!";

    #check how old the file is
    $howold = -M IN;

    #copy old files 
    if($howold > $days) {
  
      $outfile = $outdir.'/'.@files[$i];
      open(OUT, " > $outfile") or die "can't open $outfile: $!";
        while($line = < IN >) {
           print OUT $line;
        }
      close(OUT) or die "can't close $outfile: $!";

    close(IN) or die "can't close $infile: $!";
    
    # remove the file from the original directory
    unlink($infile);
    } else {

    close(IN) or die "can't close $infile: $!";
    }

   }

}