I don't have a lot to say, but this is my little bit.

Saturday, October 27, 2012

rdir.pl - Recursively Print Directories

This code prints out a recursive list of directories without ever using the `ls` command. This code instead uses the perl `stat` function to get information about a file.
#!/usr/bin/perl
use strict;
use File::Basename;

# rdir.pl
# by Nicholas Keene, September 2012
# script for candidate evaluation for CHTC
#
# As described on http://research.cs.wisc.edu/condor/hiring/test4/test4.html this script takes one
# directory as a parameter then recursively prints formatted directory and file information for that
# directory without using `ls`.

my ($dirpath) = @ARGV;

# Threshold must be an integer
if (-d $dirpath) {
 RecursivelyPrintDir($dirpath);
} else {
    print "Specified path must be a directory.\n";
}

# RecursivelyPrintDir
# Takes the name of a directory (note: does not verify the directory)
# Prints directory name and all regular files within it
# Then recursively calls itself on all dirs within it
sub RecursivelyPrintDir { 
 my ($dirpath, @dirs);
 $dirpath = shift;
 
 printf "Directory <%s>\n", $dirpath; 
 foreach my $file (<$dirpath/*>) {
  if(-d $file) {
   push (@dirs, $file);
  } else {
   my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat $file;
   my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($mtime);
   printf " %10s %4s-%02s-%02s %02s:%02s:%02s  %s\n", $size, $year+1900, $mon, $mday, $hour, $min, $sec, basename($file);
  }
 }
 print "\n";
 
 foreach $dirpath (@dirs) {
  RecursivelyPrintDir($dirpath);
 } 
}

No comments:

Post a Comment