Featured post
perl - Why doesn't the recursive function call not change the execution flow? -
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 execute above code, first prints contents of current directory , goes on list contents of subdirectory. should not go sub-dir once encounters sub-dir, list files inside , resume parent folder?
thanks.
[edit, in response orangedog]
i'm using code on windows. output this:
a.txt
b.txt
dir: ./images
c.txt
d.txt
... [and images folder listed]
./images/qwe.jpg
./images/asd.jpg
./images/zxc.jpg
...
you've got bunch of problems here. here's version works:
use strict; use warnings; sub dir_list1 { $path = $_[0]; (<$path/*>) { if (-f $_) { print "$_\n"; } else { print "enter dir: $_\n"; dir_list1($_); print "leave dir: $_\n"; } } } dir_list1(".");
things wrong original code:
- lack of
use strict; use warnings;
- not using lexical variable
$path
- using quotes around variable redundant (
"$_"
) - the filenames returned glob operator include path gave it
but fundamental problem glob operator in scalar context can't used recursively. iterator uses tied particular line of code. when recurse, iterator still returning filenames parent directory.
i changed while
(scalar context) for
(list context). for
loop generates complete list of filenames , iterates on it, , can used recursively.
i'm assuming you're doing learning exercise. otherwise, ought using 1 of many modules finding files. here's partial list:
- file::find - classic, core module since 5.000. annoying interface.
- file::find::rule - wraps file::find in nicer interface
- file::next - has iterator-based interface avoids having read entire directory tree before returning anything
- path::class::iterator - file::next, magic filename objects of path::class
i'm sure there's more i've overlooked.
- Get link
- X
- Other Apps
Comments
Post a Comment