5
Aug/09
0

use Path::Class;

The CPAN (Comprehensive Perl Archive Network) distribution, Path::Class, provides a simple OO API alternative to the built-in perl file IO functions such as open, opendir, stat, etc. Code written to use Path::Class tends to be smaller (concise, easier to maintain, etc) than similar code that uses the standard built-in functions.

Here is an example of how a small utility might be written without Path::Class:

print "Find all files that are less than 10k in size...\n";

my $dir = '/some/dir';
opendir( DIR, $dir );
    my @files = readdir( DIR );
closedir( DIR );

foreach my $file (@files) {
    next if !-f "$dir/$file";
    if ( (stat "$dir/$file")[7] < 1024 * 10) {
        print "$dir/$file\n";
    }
}

And here it is re-written to use Path::Class:

use Path::Class;
print "Find all files that are less than 10k in size...\n";

my $dir = dir('/some/dir');

while (my $file = $dir->next()) {
    next if $file->is_dir();
    if ($file->stat->size() < 1024 * 10) {
        print "$file\n";
    }
}

Using Path::Class is a no-brainer when you compare `(stat "$dir/$file")[7]` with `$file->stat->size()`.

One of Path::Class’s greatest stengths is that it is very simple and many of the features it provides are done so by glueing with other well-tested modules that have been on CPAN for a long time. These modules include IO::Dir, IO::File, File::Path, and File::stat.

Some other highlights include:

  • Has a recurse() method that provides an enhanced File::Find-like interface.
  • Works equally well with absolute and relative paths, and can correctly convert between the two.
  • Symlinks are handled correctly and there are methods to interact with them.
  • Works equally well under different operating systems, such as Linux and Windows.
  • The interface, for me anyway, is about as intuitive as it gets. Very well designed to DWIM.

I’ve been using this module at $work for a while now and am very happy with it and have had coworkers tell me, after they gave it a try, how much cleaner their code ended up being because they used this module.

Enjoy!

Tagged as:
Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

No trackbacks yet.