in reply to How do I recursively create a directory tree/filesystem?
First, I added use strict and made a couple changes to make that work. I also removed the pointless return 0;.
Next, I removed the chdir and changed the recursion line to:
This avoids changing the directory and leaves you where you were if the program quits midway through for some reason.MakeDirs("$base/$dir_name", $num_dirs, $depth - 1);
Finally, I removed the mkdir loop, and added mkdir $base; near the top of the program. This makes every recursion make one directory, which is how I like my recursion to work. It also has the added advantage of creating the initial directory if it doesn't exist.
My finished code follows:
#!/usr/bin/perl use strict; use warnings; sub MakeDirs($$$); MakeDirs("/hpq", 2, 3); sub MakeDirs($$$) { my($base, $num_dirs, $depth) = @_; mkdir $base; #if depth = 0, no more subdirectories need to be created if($depth == 0) { return 0; } #Recurse through the directories my $dir_name = "a"; for(my $x = 0; $x < $num_dirs; $x++) { MakeDirs("$base/$dir_name", $num_dirs, $depth - 1); $dir_name++; } }
|
|---|