Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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).

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top