tags:

views:

37

answers:

4

I have a perl script that will perform some operations on directories, and I only wait it to run on directories for which the current user(e.g. the user executing the script) has ownership.

I've tried the following:

...
my $user = getlogin();
opendir(HANDLE, $path) or die ("No such directory: $path");
foreach my $directory (readdir HANDLE)
{
    opendir(WORKING_DIR_HANDLE, "$path/$directory") or die ("!!!!!!!");
    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat(WORKING_DIR_HANDLE);
    my $owner = getpwuid($uid);
    if( $owner eq $user )
    {
      ...
    }
}
...

The code works for the most part. However, the call to stat() returns undefined values. According to the perl docs, I think I am making the stat() call correctly:

* stat FILEHANDLE
* stat EXPR
* stat DIRHANDLE
* stat

 Returns a 13-element list giving the status info for a file, either the file opened via
 FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is omitted, it stats $_ . Returns the 
 empty list if stat fails. Typically used as follows:

I have also tried just pasing it an EXPR using the file name, and I get the same results. Am I just missing something obvious? Or is there another way to do this? I would prefer a solution that does not require installing third-party perl modules.

+1  A: 

stat returns an empty list on failure, which sets all those variables to undef. Add or die $! after the call to find out why it failed:

my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
   = stat(WORKING_DIR_HANDLE) or die $!;

Once you know why it failed, you may be able to figure out how to fix it. If not, then add the error message to your question.

cjm
I needed to be passing in an absolute path it turns out, and the $! helped me figure that out. Thanks.
Dr. Watson
@Dr. Watson, that's strange. I would have expected it to die at the `opendir` if the path was incorrect. You were checking that return value.
cjm
+1  A: 

Try adding some error handling, e.g. after stat:

if ($!) {
   warn "WRN: $path/$directory: $!";
   next;
}

If your script takes long time to run, some directories (and files) might be moved/removed by the users (or background jobs).

Dummy00001
Thanks for the $! tip, I will definitely make sure of it from now on.
Dr. Watson
A: 

stat DIRHANDLE is a fairly new feature, and if I recall correctly not available on every platform...are you sure your perl supports it?

You may want to focus on getting stat EXPR working for you first.

ysth
A: 

You can also test whether the file/directory is owned by the current user by using -o

Hasturkun