develooper Front page | perl.perl5.porters | Postings from May 2013

RFC: Adding File::stat type test methods

Thread Next
Paul "LeoNerd" Evans
May 14, 2013 14:41
RFC: Adding File::stat type test methods
Message ID:
I notice that File::stat is core, and currently provides a fairly
spartan set of accessor methods. I have an idea to make it a little
nicer to use, and to allow for some funky additions (likely via CPAN)

Currently lots of code will do something like

  use Fcntl qw( S_IFDIR S_IFMT );
  if( stat($file)->mode & S_IFMT == S_IFDIR ) ...
  use Fcntl qw( S_ISDIR );
  if( S_ISDIR(stat($file)->mode) ) ....

I'd like to propose a simple addition of these as methods of File::stat:

  if( stat($file)->ISDIR ) ...

or maybe S_ISDIR, or isdir or.. dunno. Name isn't important - we can
discuss that.

It would make code a little neater, and most specifically, would
decouple an important POSIXism from the underlying API - namely, that
there's a set of mode bits that encodes the filetype and permissions,
and bitmasking some of them out will yield a number that decides if
it's a directory, etc..

Decoupling that may lead the way to some slightly nicer/better/more
efficient ways to provide a stat()-like function on non-POSIX platforms.

The other thing I was thinking was that currently, this code has to
perform a stat() call for every readdir() reply:

  my @dirs = grep { -d } readdir($dirh);

However, if we moved some code around we could allow

  my @dirs = grep { stat($_)->isdir } readdir($dirh)

on e.g. Linux to use getdents(3) and provide the d_type magic hint,
somehow, out of readdir(). The stat() can then be a little lazy when
presented with such a magic-overloaded hint, saving the real underlying
stat(2) call for later when another method is called, but if the only
method is something like ->isdir, it can use the type itself. Hey
presto - efficient transparent getdents() wrapping.

Anyway, all of that can be done elsewhere on CPAN; the only question
for core is: should we add these convenience methods? I think we should
as they're tiny, easy to implement, and obviously quite useful for
users to call.

I'm happy to provide a patch if it will be generally accepted.

Paul "LeoNerd" Evans
ICQ# 4135350       |  Registered Linux# 179460

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About