Perl file write test - How to determine if you can write to a file

Perl file writing FAQ: How can I test to see if I can write to a file in Perl?

In Perl it's very simple to determine whether you can write to a file. Just use the Perl -w file operator, as shown in this example:

# a simple perl 'file write' test
$filename = 'tempfile.pl';
if (-w $filename) {
  print "i can write to the file\n";
} else {
  print "yikes, i can't write to the file!\n";
}

As you can see, it's easy to test to see if you can write to a file in Perl. Testing early like this lets you find errors earlier, and deal with them more gracefully.

Perl file writing test - effective uid/gid versus real uid/gid

Note that the -w operator uses the effective uid or gid of the current user when making this determination. If for some reason you need to perform this test with the real uid or gid of the current user, you would use the -W test, like this:

$filename = 'tempfile.pl';
if (-W $filename) {
  print "i can write the file\n";
} else {
  print "yikes, i can't write the file!\n";
}

As a practical matter I almost always use the first Perl file test (the -w operator), but I thought I better mention this distinction.