12.3 Sample Object-Oriented Interface: File::Spec

Contrast the subroutines imported by File::Basename with what another core (non-CPAN) module has by looking at File::Spec. The File::Spec module is designed to support operations commonly performed on file specifications. (A file specification is usually a file or directory name, but it may be a name of a file that doesn't existin which case, it's not really a filename, is it?)

Unlike the File::Basename module, the File::Spec module has a primarily object-oriented interface. Saying:

use File::Spec;

in your program imports no subroutines into the current package. Instead, you're expected to access the functionality of the module using class methods:

my $filespec = File::Spec->catfile( $homedir{gilligan},
      'web_docs', 'photos', 'USS_Minnow.gif' );

This calls the class method catfile of the File::Spec class, building a path appropriate for the local operating system, and returns a single string.[6] This is similar in syntax to the nearly two dozen other operations provided by File::Spec: they're all called as class methods. No instances are ever created.

[6] That string might be something like /home/gilligan/web_docs/photos/USS_Minnow.gif on a Unix system. On a Windows system, it would typically use backslashes as directory separators. As you can see, this module lets you write portable code easily, at least where file specs are concerned.

While it is never stated in the documentation, perhaps the purpose of creating these as class methods rather than as imported subroutines is to free the user of the module from having to worry about namespace collisions (as you saw for dirname in the previous section). The idea of an object class without objects, however, seems a bit off kilter. Perhaps, that's why the module's author also provides a more traditional interface with:

use File::Spec::Functions qw(catfile curdir);

in which two of the File::Spec's many functions are imported as ordinary callable subroutines:

my $filespec = catfile( $homedir{gilligan},
      'web_docs', 'photos', 'USS_Minnow.gif' );