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

In reply to Re: How do I recursively create a directory tree/filesystem? by Ionitor
in thread How do I recursively create a directory tree/filesystem? by fensterblick

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.