Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
add 09-11-all-files-lazy.pl
- Loading branch information
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| use v6; | ||
|
|
||
| =begin pod | ||
| =TITLE Process files lazy | ||
| =AUTHOR gfldex | ||
| You want to recurse over all files in and under a directory in a lazy fashion | ||
| and stop after the first three files are found. We filter either based on | ||
| methods of IO::Path or on a simple Str match. | ||
| =end pod | ||
|
|
||
| multi sub find-files(Str:D $dir, &filter = {True}) { | ||
| find-files($dir.IO, &filter) | ||
| } | ||
|
|
||
| multi sub find-files (IO::Path:D $dir, &filter is copy = {True}) { | ||
|
|
||
| # If the argument type of &filter is Str, we append a '/' to directories to | ||
| # allow simple Str matches against directories. | ||
|
|
||
| my &str-filter = { &filter(.d ?? .Str ~ '/' !! .Str) } if &filter.signature.params[0].type ~~ Str; | ||
|
|
||
| gather for dir($dir) { | ||
| take .IO if (&str-filter ?? str-filter(.IO) !! filter(.IO)); | ||
| take slip sort find-files($_, &filter) if .d && (&str-filter ?? str-filter .IO !! filter .IO); | ||
| } but role { | ||
|
|
||
| # We mixin a role into the returned Seq to provide one extra method. Calling | ||
| # .head would do the same thing but would be less instructive. | ||
|
|
||
| method top(Seq:D: Int $amount){ | ||
| my $counter = $amount; | ||
| gather for self { | ||
| take $counter-- ?? $_ !! IterationEnd; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| sub MAIN(:$dir = "..") { | ||
| my \files = find-files($dir, { | ||
| (.d && .ends-with(none <tmp mnt>) ) # any directory that doesn't end in tmp or mnt | ||
| || .ends-with(any <.pl .md>) # any file or symlink, etc, that end in .pl and .md | ||
| } ); | ||
|
|
||
| for files.top(3) -> $path { | ||
| say $path.Str; | ||
| } | ||
|
|
||
| for find-files($dir, -> Str $_ {.ends-with(none <.md 04arrays/>)}) { | ||
| say .d ?? .Str ~ '/' !! .Str; | ||
| } | ||
| } | ||
|
|
||
| # vim: expandtab shiftwidth=4 ft=perl6 |