0

I was reading how-do-i-read-in-the-contents-of-a-directory and wanted to find out more about doing it without opening and closing directories as shown in @davidprecious' answer. Tried to read up on DirHandle (hoped for more explanation and example) and several other places simply redirected me to the same perldoc page. Still unsure about where to stipulate the path to read.

Say if I wanted the contents of "E:\parent\sub1\sub2\" and put that into a string variable like $p, where do I mention $p when using Dirhandle?

Would appreciate some guidance. Thanks.

user110084
  • 279
  • 2
  • 13

2 Answers2

2

Personally, I'd suggest that's too complicated, and what you probably want is glob:

#!/usr/bin/env perl

use strict;
use warnings;

foreach my $file ( glob "E:\\parent\\sub1\\sub2\\*" ) {
   print $file,"\n";
}

Although note - glob gives you the path to the file, not the filename. That's (IMO) generally more useful, because you can just pass the result to open, where if you're doing a readdir you get a file name and need to stick a path on it.

However if you do want to persist with doing it via DirHandle:

#!/usr/bin/env perl

use strict;
use warnings;
use DirHandle;

my $dir_handle = DirHandle -> new ( "C:\\Users\\Rolison\\" ); 
while ( my $entry = $dir_handle -> read ) {
   print $entry,"\n";
}

Don't use $p as a variable name - single character variable names are almost always bad style.

Sobrique
  • 52,974
  • 7
  • 60
  • 101
  • 1
    The problem with `glob` is that you can do `glob(quotemeta($dir) . '/*')` on non-Windows machines, but I seem to remember this failing on Windows machine because the escaping rules there are really weird (to allow `c:\foo`). – ikegami Oct 17 '16 at 16:16
  • Thank you @Sobrique. Grateful for the example too. Very helpful to see that. The same question I was referring to also show glob and highlighted not allowing for spaces in the path name (although not an issue for me here). Also, appreciate your comment about single character variable names - it was originally $pth which I truncated to just $p for the question. Will refrain from doing that in future. – user110084 Oct 17 '16 at 16:31
1

It's probably worth pointing out that Windows is quite happy to use forward slashes (/) as directory separators - which avoids having to have all those ugly double backslashes.

my $dir_handle = DirHandle->new('E:/parent/sub1/sub2/');
while ( my $entry = $dir_handle->read ) {
  say $entry;
}
Dave Cross
  • 68,119
  • 3
  • 51
  • 97