Skip to content

Instantly share code, notes, and snippets.

@moritz
Created June 27, 2012 11:22
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save moritz/3003456 to your computer and use it in GitHub Desktop.
Experiments with &dir for Perl 6
my class IO::Path is Cool does IO::FileTestable {
has Str $.file;
has Str $.dir = '.';
multi method Str(IO::Path:D:) {
self.file;
}
multi method gist(IO::Path:D:) {
"{self.^name}<{self.path}>";
}
multi method Numeric(IO::Path:D:) {
self.file.Numeric;
}
multi method Bridge(IO::Path:D:) {
self.file.Bridge;
}
multi method Int(IO::Path:D:) {
self.file.Int;
}
method path(IO::Path:D:) {
$.dir eq '.' ?? $.file !! join('/', $.dir, $.file);
}
method IO(IO::Path:D:) {
IO.new(:$.path);
}
}
my class IO::File is IO::Path {
method open(IO::File:D: *%opts) {
open($.path, |%opts);
}
}
my class IO::Dir is IO::Path {
method contents() {
dir($.path);
}
}
sub dir(Cool $path = '.', Mu :$test = none('.', '..')) {
my Mu $RSA := pir::new__PS('OS').readdir(nqp::unbox_s($path.Str));
my int $elems = pir::set__IP($RSA);
my @res;
loop (my int $i = 0; $i < $elems; $i = $i + 1) {
my Str $file := nqp::p6box_s(nqp::atpos($RSA, $i));
if $file ~~ $test {
my $f = IO::File.new(:$file, :dir($path));
@res.push: $f.d ?? IO::Dir.new(:$file, :dir($path)) !! $f;
}
}
return @res;
CATCH {
default {
X::IO::Dir.new(
:$path,
os-error => .Str,
).throw;
}
}
}
for dir()[^10] {
.say;
}
my class IO::File is Cool does IO::FileTestable {
has Str $.file;
has Str $.dir = '.';
multi method Str(IO::File:D:) {
self.file;
}
multi method gist(IO::File:D:) {
"IO::File<$.path>";
}
multi method Numeric(IO::File:D:) {
self.file.Numeric;
}
multi method Bridge(IO::File:D:) {
self.file.Bridge;
}
multi method Int(IO::File:D:) {
self.file.Int;
}
method path(IO::File:D:) {
$.dir eq '.' ?? $.file !! join('/', $.dir, $.file);
}
method open(IO::File:D: *%opts) {
open($.path, |%opts);
}
}
sub dir(Cool $path = '.', Mu :$test = none('.', '..')) {
my Mu $RSA := pir::new__PS('OS').readdir(nqp::unbox_s($path.Str));
my int $elems = pir::set__IP($RSA);
my @res;
loop (my int $i = 0; $i < $elems; $i = $i + 1) {
my Str $file := nqp::p6box_s(nqp::atpos($RSA, $i));
@res.push: IO::File.new(:$file, :dir($path)) if $test.ACCEPTS($file);
}
return @res;
CATCH {
default {
X::IO::Dir.new(
:$path,
os-error => .Str,
).throw;
}
}
}
for dir() {
.say if .f && /<+[A..Z]>/;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment