Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: How do I recursively create a directory tree/filesystem?

by Ionitor (Scribe)
on Jul 22, 2002 at 00:30 UTC ( [id://183902]=note: print w/replies, xml ) Need Help??


in reply to How do I recursively create a directory tree/filesystem?

The major problem here is that you're using chdir and not returning to the right directory afterwards. Since you're changing the directory of the program, the recursion doesn't work. The fastest way to fix the problem is to add chdir '..'; before return 0;. There's a couple of other changes you might want to make described below, one of which is to avoid chdir entirely.

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:

MakeDirs("$base/$dir_name", $num_dirs, $depth - 1);
This avoids changing the directory and leaves you where you were if the program quits midway through for some reason.

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++; } }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://183902]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-19 05:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found