in reply to how to create folders

opendir DIR, "the/base/directory" or die $!; my @dirs = readdir DIR; closedir DIR; shift @dirs; # remove .. shift @dirs; # and . @dirs = sort @dirs; my $highest = $dirs[-1]; $highest =~ s/\D//g; $highest += 1000; my $limit = $highest + 10000; while ($highest < $limit) { mkdir "object$highest"; $highest += 1000; }

pretty simple ;)

Replies are listed 'Best First'.
Re^2: how to create folders
by GrandFather (Saint) on Mar 28, 2007 at 08:34 UTC

    The two shifts are rather OS dependent and may cause a little grief if the code is run in a root directory. The code isn't very tolerant of foibles like unfortunately named files or directories - especially if they sort higher than the directories of interest.

    Your while loop could be turned into a for loop:

    my $start = ($highest / 1000) + 1; mkdir "object${_}000" for $start .. $start + 9;

    DWIM is Perl's answer to Gödel
Re^2: how to create folders
by Peamasii (Sexton) on Mar 28, 2007 at 09:01 UTC
    Excellent, I only had to make some small modifications, like:
    my @dirs = grep { /object...000/ && -d "$_" } readdir(DIR); ... mkdir "object$highest"; chown $uid, $gid, "object$highest"; chmod 0777, "object$highest"; ...
    Thanks so much!
      You could do it somewhat smarter and extract just the numbers:
      my @numbers = map /object(\d+)000/, grep -d, readdir(DIR);

      You can even directly pull out the highest number by using max out of List::Util:

      use List::Util 'max'; my $highest = max map /object(\d+)000/, grep -d, readdir(DIR);

      And using glob instead of readdir can help you wead out the unwanted files before trying to process them, if there's a lot of other stuff in the directory you may be not interested in:

      my $highest = max map /object(\d+)000/, grep -d, glob 'object???000';