Sort files by date modified or accessed


/ Published in: Perl
Save to your folder(s)

Lists last modified (or accessed) files. Based on a hint by Master Jedai at http://www.developpez.net/forums/showpost.php?p=2302596&postcount=4


Copy this code and paste it in your HTML
  1. #!/usr/bin/perl -w
  2. use strict;
  3. # use File::stat; # for detailed print out
  4. use Getopt::Std;
  5. #
  6. ### get options and the argument from the command line
  7. my %opts;
  8. getopts("amc", \%opts);
  9. my $operator='-M'; # date modified to present
  10. if ($opts{'a'}) {$op='-A'}; # date accessed to present
  11. if ($opts{'c'}) {$op='-C'}; # inode change time to present
  12. #
  13. my $path = shift
  14. or die "Usage: $0 [ -a | -m | -c] path\n";
  15. opendir my($dir), $path
  16. or die "Can't open $path : $!\n";
  17.  
  18. #
  19. ### store file names sorted by modification or access date
  20. #
  21. my @files = sort { eval($operator.' "$path/$a" <=> '.$operator.' "$path/$b"') }
  22. grep { -f "$path/$_" }
  23. readdir $dir;
  24. #
  25. ### with -M operator in clear
  26. #
  27. # my @files = sort { -M "$path/$a" <=> -M "$path/$b" }
  28. # grep { -f "$path/$_" }
  29. # readdir $dir;
  30. ### same with -A and -C
  31. #
  32. closedir $dir;
  33. #
  34. ### Simple print out
  35. # foreach my $file (@files) {print "$file\n";};
  36. #
  37. ### Detailed print out
  38. # foreach my $file (@files) {my $sb = stat("$path/$file"); printf "%s : last modified on %s, last accessed on %s\n", $file, scalar localtime $sb->mtime, scalar localtime $sb->atime;}

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.