Documentation for sub dir

Documentation for sub dir, assembled from the following types:

class IO::Path

From IO::Path

(IO::Path) routine dir

Defined as:

sub    dir(Cool $path = '.'Mu :$test = none('.''..'))
method dir(IO::Path:D: Mu :$test = none('.''..'))

Returns the contents of a directory as a lazy list of IO::Path objects representing relative paths, filtered by smart-matching their names (as strings) against the :test parameter.

NOTE: a dir call opens a directory for reading, which counts towards maximum per-process open files for your program. Be sure to exhaust returned Seq before doing something like recursively performing more dir calls. You can exhaust it by assigning to a @-sigiled variable or simply looping over it. Note how examples below push further dirs to look through into an Array, rather than immediately calling dir on them. See also IO::Dir module that gives you finer control over closing dir handles.

Examples:

# To iterate over the contents of the current directory: 
for dir() -> $file {
    say $file;
}
 
# As before, but include even '.' and '..' which are filtered out by 
# the default :test matcher: 
for dir(test => *-> $file {
    say $file;
}
 
# To get the names of all .jpg and .jpeg files in ~/Downloads: 
my @jpegs = $*HOME.dir: test => /:i '.' jpe?$/;

An example program that lists all files and directories recursively:

sub MAIN($dir = '.'{
    my @todo = $dir.IO;
    while @todo {
        for @todo.pop.dir -> $path {
            say $path.Str;
            @todo.push: $path if $path.d;
        }
    }
}

A lazy way to find the first three files ending in ".p6" recursively starting from the current directory:

my @stack = '.'.IO;
my $perl-files = gather while @stack {
    with @stack.pop {
        when :d { @stack.append: .dir }
        .take when .extension.lc eq 'p6'
    }
}
.put for $perl-files[^3];