views:

51

answers:

2

I want to get the details of a directory as like number of files and subdirectories in it and permissions for those.

Yes! it's easy to do it on linux machines using back ticks to execute a command.But is there a way to make the script platform independent.

thanks :)

+3  A: 

You can use directory handles (opendir and readdir) to get the contents of directories and File::stat to get the permissions

cubabit
This is a good solution if (unlike my Path::Class example) you only want to use core modules that are distributed with Perl itself.
Mark Fowler
+2  A: 

You might want to consider using Path::Class. This both gives you an easy interface and also handles all the cross platform things (including the difference between "\" and "/" on your platform) for you.

   use Path::Class qw(file dir);

   my $dir = dir("/etc");

   my $dir_count = 0;
   my $file_count = 0;

   while (my $file = $dir->next) {
       # $file is a Path::Class::File or Path::Class::Dir object

       if ($file->is_dir) {
         $dir_count++;
       } else {
         $file_count++;
       }

       my $mode = $file->stat->mode;
       $mode = sprintf '%o', $mode;  # convert to octal "0755" form
       print "Found $file, with mode $mode\n";
   }
   print "Found $dir_count dirs and $file_count files\n";
Mark Fowler
What if you can't stat the file? Then undef->mode won't work...but you've already counted it in $file_count.
oylenshpeegul
@oslenshpeegul: What situations exist where would I not be able to stat the file? I've just successfully read in the contents of the directory...
Mark Fowler