The 2003 Perl Advent Calendar
[about] | [archives] | [contact] | [home]

On the 15th day of Advent my True Language brought to me..
Text::Glob

One of the keys to writing good code is using the right tool for the job. The whole reason why Perl regular expressions are so popular is because they're a completely separate little language within Perl for doing a distinct job. In theory, someone could have written a module with which you could specify a program method call by method call to build up a regular expression matcher - but writing in a domain particular language is much easier

The closer to the domain of the problem the easier it is to code programs in this domain. Text::Glob is an example of an even more domain specific language than regular expressions, not only optimised for matching text buy highly optimised for specifying patterns for matching file names. It allows you to directly use the syntax that you're familiar with from using the shell directly in your Perl programs. Sure, you could do this with a regular expression, but it's much harder to deal with and a lot less clear for the reader - especially if you deal with the edge cases.

Text::Glob can be made to export two functions, glob_to_regex and match_glob. The former of these returns a compiled perl regular expression that implements the glob pattern, whereas the latter applies the glob pattern directly to a list.

  use Text::Glob qw(glob_to_regex);
  my $regex = glob_to_regex("*.pm");
  my @perlfiles = grep /$regex/, @files;
  use Test::Glob qw(match_glob);
  my @perlfiles = match_glob("*.pm", @files);

And that's about it, apart from describing the syntax.

So there you have it, another simple but immensely useful module.

  • File::Find::Rule uses Text::Glob schemantics
  • perlre manual page