Core Modules: filetest

The filetest pragma modifies the behavior of the file test operators (a.k.a. the -X operators.) It has been in core since Perl 5.6.0.

As of Perl 5.36.0 it still has only one sub-pragma, 'access', which applies to the -r, -w, -x, -R, -W, and -X tests. Normally, these tests only consider the mode bits returned by stat(), as discussed in my previous blog post, The File Access Operators: To Use, or Not to Use. But within the scope of use filetest 'access';, these tests consider not only the mode bits, but any ACLs (Access Control Lists) that may be applied to the file -- at least, under POSIX systems. Under systems that do not implement access(), this sub-pragma does nothing.

Taking ACLs into account sounds like a Good Thing, but it comes at a price. Within the scope of the 'access' sub-pragma:

  • You can not test a handle, only a file name;
  • The _ (underscore) special file handle is not set by the access tests;
  • As a consequence of this, stacked file test operators may not work either;
  • There may be a speed penalty.

The situation with _ is particularly vexing, because its use is not an error of any sort -- you just get the wrong result.

On the other hand, and as you would probably expect, use of the topic variable $_ appears to work as expected; that is, something like -w and say 'Writable'; works whether or not use filetest 'access'; is in effect.

My conclusion is that you should use the filetest pragma if it makes sense to do so, but you should be careful to limit the scope of the pragma, and comment what is going on. Maybe something like the following fragment is in order, which assumes the name of the file is in $file:

    printf "%s %s writable per stat() bits\n",
	$file, -w $file ? 'is' : 'is not';
    {
	use filetest 'access';
	# NOT -w _, because -w now ignores it
	printf "%s %s writable per stat() bits and ACL if any\n",
	    $file, -w $file ? 'is' : 'is not';
    }

Why not "My Favorite Module?" Probably because, given The File Access Operators: To Use, or Not to Use, it may be better not to use the file access operators at all if they can be avoided. The best way to find out if you can write a file is to try to do so.

Previous entries in this series:

  1. if
  2. diagnostics
  3. Term::ReadLine::Perl
  4. re
  5. Devel::NYTProf
  6. Errno
  7. Time::Piece

1 Comment

Just wanted to say "Thank You". These posts have been quite informative.

Leave a comment

About Tom Wyant

user-pic I blog about Perl.