sub dir_list1
{
$path=$_[0];
while(<$path/*>){
if (-f "$_"){
print "$path/$_\n";
}
else {
print "dir: $path/$_\n";# if ($entry ne "." && $entry ne "..");
dir_list1($_);
}
}
}
dir_list1(".");
When i execute the above code, it first prints ALL the contents of the current directory and then goes on to list the contents of the subdirectory. Should it not go into the sub-dir once it encounters a sub-dir, list the files inside and resume with the parent folder?
Thanks.
[Edit, in response to OrangeDog]
I’m using this code on windows. The output is something like this:
a.txt
b.txt
dir: ./images
c.txt
d.txt
…
[and then the images folder is listed]
./images/qwe.jpg
./images/asd.jpg
./images/zxc.jpg
…
You’ve got a bunch of problems here. Here’s a version that actually works:
Things wrong with the original code:
use strict; use warnings;$path"$_")But the fundamental problem was that the glob operator in scalar context can’t be used recursively. The iterator it uses is tied to that particular line of code. When you recurse, the iterator is still returning filenames from the parent directory.
I changed your
while(scalar context) to afor(list context). Aforloop generates the complete list of filenames and then iterates over it, and it can be used recursively.I’m assuming you’re doing this as a learning exercise. Otherwise, you ought to be using one of the many modules for finding files. Here’s a partial list:
I’m sure there’s more I’ve overlooked.