Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Descending a directory tree, returning a list of files

by kennethk (Abbot)
on Jun 09, 2015 at 20:18 UTC ( [id://1129697]=note: print w/replies, xml ) Need Help??


in reply to Descending a directory tree, returning a list of files

Since you've used a bareword directory handle, you clobber your existing handle every time you descend a level. Never use bareword handles for recursive calls. Problem solved if you use a lexical/indirect handle:
use strict; use warnings; use Cwd 'getcwd'; ## cwd my $cwd = getcwd; ## Get files from cwd my $res = _list_files($cwd); sub _list_files { my $dir = shift; my $files = shift; opendir(my $dh, $dir) || die "Error opening: $dir\n"; while (my $fn = readdir($dh)) { ## skip hidden next if $fn =~ /^\./; ## file, fullpath name my $file = $dir . "/" . $fn; ## add push(@{ $files }, $file); ## dir, decend if (-d $file) { ## sub-directory files $files = _list_files($file, $files); } } #closedir($dh); # Not necessary; auto-closed on end of scope return $files; }
See also How do I traverse a directory tree?

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Replies are listed 'Best First'.
Re^2: Descending a directory tree, returning a list of files
by Rodster001 (Pilgrim) on Jun 09, 2015 at 20:22 UTC
    That was it. Bareword directory handle. For some reason I thought that was private to that sub routine. Thank you!
      Forgetting that bareword handles are global is a common issue, which is why (for me at least) Bareword Handles Considered Harmful.

      #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

        They are now officially a thing of the past. I'll never use em' again :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1129697]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2024-04-23 11:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found