perlfile-permissions

Perl: Testing that a file is actually writable as opposed to checking file permissions


Say I have a file /var/tmp/filename.

In Perl, I write the following snippet:

#!/usr/bin/env perl
use strict;
use warnings;

if (-W /var/tmp/filename)
{
...
}

exit;

Will the -W and -w functions (http://perldoc.perl.org/functions/-X.html) check that the file can actually be written to, or only check that the file permissions allow writing?

The reason I ask is that I am writing a script which retrieves a cookie.

This script needs to be able to write the cookie file to the filesystem, but if the filesystem path to the cookie file is read only, the permissions on the file won't matter. So I want to test if the cookiefile is actually writable as opposed to just checking its permissions.


Solution

  • If your concern is the filesystem, you can check whether it is mounted read-only. If so, its line in /proc/mounts will have ro, so open the file and grep for lines with ro and your filesystem.

    This will work only on filesystems that use /proc but yours do.

    Note that querying with mount is less reliable.

    A sure-fire way is to attempt to write a file, and I'd use File::Temp for that.