A problem of searching through directories
I have encounter a problem in which i need to scan over all the files
within a directory tree. My script is like the following
#!/usr/bin/perl -w
$d = "some directory here";
chop($d);
&searchDirectory($d);
sub searchDirectory {
local($dir);
local( [at] lines1);
local($line);
local($subdir);
$dir = $_[0];
print "$dir\n";
[at] lines1 = `cd $dir;ls -A|cat`;
foreach ( [at] lines1){
# do something here
}
[at] lines2 = `cd $dir;ls -l`;
foreach $line ( [at] lines2) {
if($line =~ /^d/) {
$line =~ /\s+(\S+)$/;
$subdir = $dir."/".$1;
&searchDirectory($subdir)
}
}
}
It does not work as expected, for example there are /a/a1/a2, /b/b1/b2,
/c/c1/c2, my expectation would be that it scan through all those files,
but it turned out that it only work with one subdirectory, and only one
sub of the sub....
Can anyone offer some hint?
--
To unsubscribe, e-mail: beginners-unsubscribe [at] perl.org
For additional commands, e-mail: beginners-help [at] perl.org
http://learn.perl.org/
Re: A problem of searching through directories
>>>>> "LY" == Li Yi <liyionline1991 [at] gmail.com> writes:
LY> I have encounter a problem in which i need to scan over all the files
LY> within a directory tree. My script is like the following
before we get into your code, where are you learning perl? this is very
old style perl. it is perl 4 to be exact which is very very old and not
used anymore. please upgrade your perl and your learning sources.
LY> #!/usr/bin/perl -w
use warnings is better.
use strict is needed.
LY> $d = "some directory here";
LY> chop($d);
chomp is the correct call now.
LY> &searchDirectory($d);
subs don't need to be called with &.
LY> sub searchDirectory {
LY> local($dir);
LY> local( [at] lines1);
LY> local($line);
LY> local($subdir);
those should be my variables, not local.
LY> $dir = $_[0];
my( $dir ) = [at] _ ;
LY> print "$dir\n";
LY> [at] lines1 = `cd $dir;ls -A|cat`;
why are you piping ls to cat? that is a useless use of cat.
and you can do that directly in perl.
LY> It does not work as expected, for example there are /a/a1/a2,
LY> /b/b1/b2, /c/c1/c2, my expectation would be that it scan through all
LY> those files, but it turned out that it only work with one
LY> subdirectory, and only one sub of the sub....
LY> Can anyone offer some hint?
use File::Find which will scan dirs for you.
but you must drop perl4 and learn perl5. seriously.
uri
--
Uri Guttman ------ uri [at] stemsystems.com -------- http://www.sysarch.com --
----- Perl Code Review , Architecture, Development, Training, Support ------
--------- Gourmet Hot Cocoa Mix ---- http://bestfriendscocoa.com ---------
--
To unsubscribe, e-mail: beginners-unsubscribe [at] perl.org
For additional commands, e-mail: beginners-help [at] perl.org
http://learn.perl.org/