IO::Glob for Perl 6

This is a module I wrote a while back, but I never announced. I am pretty happy with how this came out, so here's the announcement. Some JAPHs might be disappointed to learn that one feature of Perl 5 that did not make it to 6 is globbing. That is, doing something like this:

for my $file (glob "src/core/*.pm") { say $file }

With just Perl 6, you need to do something like this instead:

for "src/core".IO.dir(:test(/ .* ".pm" $/)) -> $file { say ~$file }

That's not too terrible, but I still miss the simplicity of globs. In that case, I can use IO::Glob:

use IO::Glob;
for glob("src/core/*.pm") -> $file { say ~$file }

That does the same thing as the Perl 5 code, more or less.

But, that's not all. I always wished that globs could be used for pattern matching. Sometimes, just matching a string against a glob is handy, but Perl 5's globs are narrow minded. IO::Glob is not:

use IO::Glob;
for <abc acc acdc>.grep(glob('ac*')) { .say }

You can apply globs to anything, though, if you really want directory/file matching-type semantics, you really want to work with IO::Path objects:

use IO::Glob;
for <abc acc acdc>.map({ .IO }).grep(glob('ac*')) { .say }

In this particular case, it does not make any difference, but the placement of a path separating slash is treated as just another character when matching strings, but is treated as a significant file separator when matching paths, so be aware of that difference.

Finally, this is nice, but there is more to globbing than just '*', right? By default, IO::Glob parses globs using a BSD-style grammar. Therefore, without doing anything special, you can use *, ?, [abc], [!abc], ~, {ab,cd,efg} and they do what you expect.

Sometimes, though, that's just overkill. You can request a simple grammar that just supports * and ?:

use IO::Glob;
for glob("src/core/*.pm", :grammar(IO::Glob::Simple)) -> $file { say ~$file }

Or you can use SQL-style globbing, if you prefer:

use IO::Glob;
for glob("src/core/%.pm", :grammar(IO::Glob::SQL)) -> $file { say ~$file }

From here you could even write your own grammar, but I am not going to go into those details here.

If you are trying out Perl 6 and find that you want to glob some files, IO::Glob is here to help.

Cheers.

1 Comment

Excellent! Thanks!. I have used this module for a script that opens files in a directory (in the form of "pattern.extension") and asks for deletion: Files.pl6

Leave a comment

About Sterling Hanenkamp

user-pic Perl hacker by day, Perl 6 module contributor by night.