Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import raku's `dir` function into Perl

Tags:

perl

raku

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.

like image 886
con Avatar asked Nov 16 '25 08:11

con


1 Answers

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$/);
like image 135
Grinnz Avatar answered Nov 19 '25 06:11

Grinnz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!