in reply to Directory recursion on win32

Although you may want to use File::Find as other respondents suggested, you can get your subroutine to work by declaring your variables with "my" inside your subroutine Recurse.
#!wperl use strict; use Win32; sub Recurse; Recurse ($ARGV[0]); sub Recurse { my ($DirItem); my ($Formatted); my ($PWD); ($PWD) = @_; opendir(DIR, $PWD); my @DirList = readdir(DIR); closedir DIR; foreach $DirItem (@DirList) { $Formatted = $DirItem . "z"; if ( -d $DirItem &&$DirItem ne "." && $DirItem ne "..") { &Recurse ($PWD . "\\" . $DirItem); } if ($DirItem ne "." && $DirItem ne "..") { rename("$PWD\\$DirItem","$PWD\\$Formatted"); } } }
Updated: Changed
  rename($DirItem,$Formatted);
to
  rename("$PWD\\$DirItem","$PWD\\$Formatted");

That should fix it.

Replies are listed 'Best First'.
Re: Re: Directory recursion on win32
by fourmi (Scribe) on Aug 04, 2003 at 14:34 UTC
    Okay, moved the definitions inside the sub, and added a count, to see how many times it recursed. Extra info is that It will rename the files (and dirs) in the current directory (so the initial given path), but it won't dig deeper. So the problem is with how i pass path info to Recurse?
      Here is a script that I wrote which recurses down a win32 directory strcuture and writes a logfile which tells the directories and all the contents.. I think the recursion model might be useful for you. Although it doesn't use File::Find
      #!/Perl/bin/perl use IO::File; use strict; print "Enter the directory to map: "; my $dir = <STDIN>; chomp($dir); my $log = new IO::File; $log->open(("> c:\\log.txt")) or die "$!"; $log->write("Map of: ".$dir."\n",length("Map of: ".$dir."\n")); $dir =~ s{\\}{\\\\}g; mapMe($dir); $log->close; ##Recursive routine to print out all the files & folders under a given + root node sub mapMe { #Get the parameter my $handle = shift; #Open the directory passed to the subroutine opendir(SPROUT,$handle); #read the entries my @entries = readdir(SPROUT); #Close the directory closedir(SPROUT); my $log_entry; #Skip the . and .. entries foreach my $i (2..scalar(@entries)) { #Format the handle for the next call my $param_handle = $handle."\\".$entries[$i]; #If its a directory and its not null if(opendir(TEST,$param_handle) and $entries[$i]) { #Close the directory closedir(TEST); #Strip the handle for log writing purposes $handle =~ s{\\\\}{\\}g; #Construct and write the log $log_entry = "\n".$handle."\\".$entries[$i]."\n"; $log->write($log_entry,length($log_entry)); #recurse the directory mapMe($param_handle); } elsif($entries[$i]) { #Construct and write the log $log_entry = "*".$entries[$i]."\n"; $log->write($log_entry,length($log_entry)); } } }