I've been learning perl6/raku for a while now, and I really like the dir routine https://docs.perl6.org/routine/dir. It's very convenient and easy to use.
Is there any way that I could import/backport dir into Perl? I am unable to get any results on internet searches.
This is very similar to what you get from readdir.
use strict;
use warnings;
open my $dh, $dirpath or die "Failed to open $dirpath: $!";
foreach my $file (readdir $dh) {
next if $file eq '.' or $file eq '..';
print "$dirpath/$file: $file\n";
}
My Dir::ls makes this a little neater, but it's designed more to emulate ls than to be programmatically useful.
use strict;
use warnings;
use Dir::ls;
foreach my $file (ls $dirpath) {
print "$dirpath/$file: $file\n";
}
Path::Tiny makes the common case easy as usual - all paths are Path::Tiny objects.
use strict;
use warnings;
use Path::Tiny;
foreach my $filepath (path($dirpath)->children) {
my $file = $filepath->basename;
print "$filepath: $file\n";
}
And it can filter on a regex (applied to the basename, not the full path):
path($dirpath)->children(qr/\.txt$/);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With