If you think of a "directory tree" as a real tree gaph, the minimum number of mkpath() calls you need is exactly the number of leaves in that tree. find() does a depth-first search, so there's a quite efficient way to determine leaves:

my $p = './a'; my @paths = (); find( sub { return unless -d; print "$File::Find::name in $File::Find::dir\n"; unless( $p eq $File::Find::dir ){ print "CH\n"; push @paths => $p; } $p = $File::Find::name; } , $p ); push @paths , $p; print "--> $_\n" for @paths; # this has been tested

The amount of saved mkpath() calls depends on the directory tree, it's still O(n) where n is the number of directories but that's only reached if the tree is super-flat (depth=1).

But why use mkpath at all? It ends up in n mkdir() calls anyways, why not do that yourself in the find-sub and save the time mkpath() needs to recognize already created directories? mkpath() is not usefull if you do directory traversal anyways. For find() uses depth-first search, it's guaranteed that the parent directory always exists.

find( sub { next unless -d; mkdir File::Spec->catpath( ... ) } , ' ... ' );
--
http://fruiture.de

In reply to Re: cloning a directory tree by fruiture
in thread cloning a directory tree by zentara

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.