Skip to content

Commit 14d8a63

Browse files
authored
rmdir: replace dirname() loop (#911)
* rmdir: replace dirname() loop * In -p mode, split a directory argument with File::Spec as recently done in mkdir * The final element of the split is ignored because that directory has already been removed by the unconditional remove() * The '/' directory will not be removed if an absolute path is given on u***nix * test1: perl rmdir -p A/B/C # relative path * test2: perl rmdir -p /a/b/c # absolute path * remove stray variable
1 parent 4068192 commit 14d8a63

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

bin/rmdir

+20-17
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,14 @@ License: perl
1414

1515
use strict;
1616

17-
use File::Basename qw(basename dirname);
17+
use File::Basename qw(basename);
18+
use File::Spec;
1819
use Getopt::Std qw(getopts);
1920

2021
use constant EX_SUCCESS => 0;
2122
use constant EX_FAILURE => 1;
2223

23-
my ($VERSION) = '1.2';
24+
my ($VERSION) = '1.3';
2425
my $Program = basename($0);
2526

2627
my $rc = EX_SUCCESS;
@@ -30,27 +31,29 @@ if (!getopts('p', \%opt) || scalar(@ARGV) == 0) {
3031
exit EX_FAILURE;
3132
}
3233
foreach my $directory (@ARGV) {
33-
unless (rmdir $directory) {
34-
warn "$Program: failed to remove '$directory': $!\n";
35-
$rc = EX_FAILURE;
36-
next;
37-
};
34+
next unless remove($directory);
3835
if ($opt{'p'}) {
39-
# Errors are ignored once in recursion.
40-
while (1) {
41-
$directory = dirname($directory);
42-
last if ($directory eq '.' || $directory eq '/');
43-
44-
unless (rmdir $directory) {
45-
warn "$Program: failed to remove '$directory': $!\n";
46-
$rc = EX_FAILURE;
47-
last;
48-
}
36+
my @parts = File::Spec->splitdir($directory);
37+
my @seq = 0 .. (scalar(@parts) - 2);
38+
for (reverse @seq) {
39+
my $d = File::Spec->catfile(@parts[0 .. $_]);
40+
next if length($d) == 0; # absolute path
41+
remove($d);
4942
}
5043
}
5144
}
5245
exit $rc;
5346

47+
sub remove {
48+
my $dir = shift;
49+
unless (rmdir $dir) {
50+
warn "$Program: failed to remove '$dir': $!\n";
51+
$rc = EX_FAILURE;
52+
return 0;
53+
}
54+
return 1;
55+
}
56+
5457
__END__
5558
5659
=pod

0 commit comments

Comments
 (0)