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

I've got this script that will read an input file of comma delimited server names, search the servers and determine the specified directory size, and output the result to a csv file. Now my only problem is when the script errors when it can't access a folder due to permissions, it then outputs a size of 0 for that directory. This isn't really correct because the directory might not be empty, it's just that it couldn't be accessed.

What I need to figure out is how to get the script to report "Error" (or something along those lines) in the output, instead of 0. Here is my code:

use File::Find; use strict; my ($dir, @parts); open(IN, "< input.csv") or die("Couldn't open input.csv\n"); open(OUT, "> output.csv") or die("Couldn't open output.csv\n"); @parts=split (/,/,<IN>); #Displays total size of specified path (total includes subfolders) foreach my $dir (@parts) { my $total; print "\nWalking $dir\n"; find(sub { $total += -s }, $dir); $total = ($total / 1024) / 1024; $total = sprintf("%0.2f", $total); print OUT "$dir, $total, mb, \n"; } print "\n\tOutput created.\n"; close(OUT); #Displays program syntax on screen $dir = $ARGV[0];

Here is an example of the contents of the input file:

\\server\share,\\server\different_share,c:\temp

Replies are listed 'Best First'.
Re: File::Find question
by Zed_Lopez (Chaplain) on Jun 06, 2003 at 20:40 UTC
    Use the -r file operator to see whether you have read permission to the directory.
    if (-r $dir) { find(sub { $total += -s }, $dir); $total = ($total / 1024) / 1024; $total = sprintf("%0.2f", $total); print OUT "$dir, $total, mb, \n"; } else { # however you want to deal with this condition }
Re: File::Find question
by converter (Priest) on Jun 07, 2003 at 19:12 UTC

    Consider using the preprocess and postprocess callback parameters to filter out and report files and directories you can't read. File::Find is recursive, so it's important to catch errors not only for the initial directory, but also for any files and directories beneath it.

    Here's an example that shows how you might do this:

Re: File::Find question
by cciulla (Friar) on Jun 06, 2003 at 19:56 UTC

    I may be missing something, but wouldn't

    if ($total == 0) { $total = "Error"; } else { $total = sprintf("%0.2f", $total); }
    work?

      That wouldn't exactly work because sometimes a directory truly may be empty, in which case I want to know that. I am wanting it to print "Error" when there is a problem accessing the files (because of permissions, file is open, etc.). I hope this is a little clearer.