#!/usr/pkg/bin/perl -w # (c) 2005/05/31 yoya@awm.jp use strict; use FileHandle; my $rm_com = 'rm'; my $rm_opt = '-rf'; sub usage { my $msg = shift; print STDERR $msg . "\n"; print STDERR "Usage: $0 remain path depth [path depth [...]]\n"; print STDERR "ex) $0 6 cap0 3 cap1 3\n"; exit 1; } MAIN: { my $argc = @ARGV; usage("too few arguments") if ($argc < 3); usage("mismatch path and depth") if (($argc % 2) == 0); my $remain = shift @ARGV; my %path_table = @ARGV; my @folder_list = (); # get target folder list foreach my $path (keys %path_table) { my $depth = $path_table{$path}; foreach my $p (get_folder_list($depth, $path)) { push @folder_list, $p; } } # create time ascend order sorting @folder_list = sort { get_ctime($a) <=> get_ctime($b) } @folder_list; # remain new folder for (1 .. $remain) { my $tail = pop @folder_list; last unless (defined($tail)); } # remove old folder foreach my $dir (@folder_list) { die "dir is empty!!" if ($dir eq ''); exec $rm_com, $rm_opt, $dir; } exit 0; } # get folder list (recursive) sub get_folder_list { my ($depth, $path) = @_; my @folder_list = (); if ($depth < 1) { return $path; } foreach my $p (get_child_folder_list($path)) { foreach my $p2 (get_folder_list($depth - 1, $path . '/' . $p)) { push @folder_list, $p2; } } return @folder_list; } # get folder list (one level only) sub get_child_folder_list { my $path = shift; my $fh = new FileHandle; my @folder_list = (); opendir($fh, $path); while(defined(my $d = readdir($fh))) { next if ($d =~ /^\.$/); next if ($d =~ /^\.\.$/); push @folder_list, $d; } closedir($fh); return @folder_list; } # get create time sub get_ctime { my $file = shift; my $fh = new FileHandle $file, "r"; my @fs = stat($fh); my $ctime = $fs[9]; close($fh); return $ctime; }