Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks!
I am trying to remove directories if they are older than 30 days from this directory, the code using "rmdir" is not working anymore, do you know if permission could be set or if it needs to be set for this line with the "rmdir" to work?
Here is a sample of the code for this issue
#!/usr/bin/perl -w use strict; use Date::Calc qw( Today Add_Delta_Days ); my $date = sprintf "%04d/%02d/%02d",Add_Delta_Days( Today(), -30 ); $date =~ s/(\d{4})\/(\d{2})\/(\d{2})/$1$2$3/; print "\n\n Deleting directory(ies) if older than 30 days::: $date \n\ +n\n"; my $dir = "/to_del"; opendir (DIR, $dir) or die "Couldn't open directory, $!"; while (my $f_dir = readdir DIR) { next if $f_dir=~/^\./; next unless (-d "$dir/$f_dir"); # 20111205 - this is the name of the directy(ies) in /to_del directo +ry , they have date for their names if($f_dir le $date){ print "\nDeleted - $f_dir\n\n"; rmdir("$dir/$f_dir") || die ("cant delete: $?"); } } closedir DIR; print "\n\n Done \n\n\n";
Thanks for the help!

Replies are listed 'Best First'.
Re: Removing directories with rmdir!
by toolic (Bishop) on Jan 05, 2012 at 20:44 UTC
    From perldoc -f rmdir:
    Deletes the directory specified by FILENAME if that directory is empty.
    Is your directory empty?

    Also, you should print $!, not $?

      No, I read on it, the directory(ies) is/ are not empty.
        What about something like this:
        #!/usr/bin/perl use strict; use warnings; use File::Path qw(remove_tree); remove_tree('dir');
Re: Removing directories with rmdir!
by ww (Archbishop) on Jan 05, 2012 at 20:44 UTC
    "is not working"

    Is not the (verbatim) error message or warning you got, not is it a description that helps us diagnose your problem. Please emend your node.

    But, on a WAG, are the directories-to-delete empty?

    perldoc -f rmdir tells you:
    Deletes the directory specified by FILENAME if that directory is empty. If it succeeds it returns true, otherwise it returns false and sets $! (errno). If FILENAME is omitted, uses $_.
    To remove a directory tree recursively ("rm -rf" on Unix) look at the "rmtree" function of the File::Path module.