in reply to Help making a directory tree

I'm pretty sure there's a module to do this, but until somebody points it out you can try something like this:
#!/usr/bin/perl -w use strict; mkdir_p($ARGV[0]); sub mkdir_p { my($d)=@_; my $dirsofar = ""; foreach my $dc (split(/\//,$d)) { next unless ($dc); $dirsofar .= "/".$dc; if (!mkdir($dirsofar)) { if ($! !~ /exists/i) { die "Couldn't mkdir($dirsofar): $!"; } } } }

Replies are listed 'Best First'.
Re: Re: Help making a directory tree
by GaijinPunch (Pilgrim) on Aug 26, 2003 at 07:52 UTC
    Thanks for the reply. One kicker here though. Your code stops when it can't make the first directory (/home in this case). Complains that the folder exists, which it will in most cases. I tried changing this:
    $dirsofar .= "/".$dc;
    to this:
    $dirsofar = ( $dirsofar =~ /^./ ) ? $dirsofar . "/".$dc : $dirsofar .= + $dc;
    In order to make directories only from the current directory. IE - if running the script from /home/user --- make the other two directories. But in that case if:
    @ARGV[0] = "/home/user/files/work/file";
    My directories would turn out to be:
    /home/useruser/filesfilesfiles/workworkworkwork
    Another 20 minutes and I should be able to to tweak your guy... I gotta bolt in a minute though. :(
      Merlyn's solution is better, but the directory already existing is why it checks the error message:
      if ($! !~ /exists/i) { die "Couldn't mkdir($dirsofar): $!"; }
      As long as the error message contains the word "exists", it will just ignore the error and continue on. I tested this case, and it worked fine for me. If it doesn't work for you, I'm curious what error message it prints...