How to find files with Path::Class::Rule

Path::Class::Rule is what you get when you imagine the love-child of Path::Class and File::Find::Rule. Here is part of the SYNOPSIS:

use Path::Class::Rule;
 
my $rule = Path::Class::Rule->new; # match anything
$rule->file->size(">10k");         # add/chain rules
 
# iterator interface
my $next = $rule->iter( @dirs );
while ( my $file = $next->() ) {   # $file is a Path::Class object
  ...
}

As you can see, it has the same method-chaining of rule helpers that File::Find::Rule does. However, it’s not built on top of File::Find, so you get a real, lazy iterator instead of the File::Find::Rule iterator that precomputes the results and hands them to you one at a time. The iterator returns Path::Class objects, which makes it a little easier to do some common file manipulations.

While Path::Class::Rule is very new, it already implements the following kinds of rule helpers:

  • File name rules
  • Directory skipping rules
  • File test rules, e.g. -f, -d, -r, -w, etc.
  • Stat test rules, e.g. results of stat()
  • Search depth rules
  • Perl file rules
  • Version control file skipping rules

It’s also easy to extend. You only need to “and” together a callback that gets $_ set to the Path::Class object under examination:

$rule->and( sub { -r -w -x $_ } ); # stacked filetest example

You can write extension classes with new helper methods using the add_helper method. Here’s a simple example that matches files named “foo”:

package Path::Class::Rule::Foo;
 
use Path::Class::Rule;
 
Path::Class::Rule->add_helper(
  foo => sub {
    my @args = @_; # do this to customize closure with arguments
    return sub {
      my ($item) = shift;
      return if $item->is_dir;
      return $item->basename =~ /^foo$/;
    }
  }
);
 
1;

If this module sounds interesting, give it a try! If you want to help improve it, fork it on Github and let me know what you have in mind.

(If you’re a curmudgeon and want to know why I wrote another file-finding module for CPAN, read the “SEE ALSO” section of the documentation for my comparison to other things out there.)

Update I’ve released 0.004 with some additional SEE ALSO entries based on suggestions below.