David B
David B

Reputation: 29998

How can I check if `File::Path::remove_tree` failed?

I'm used to `... or die ".. failed... $!";.

I was surprised to find that in order to know if File::Path::remove_tree failed or not I must do something like this:

remove_tree( 'foo/bar', 'bar/rat', {error => \my $err} );
if (@$err) {
 die "error..."
}

Am I missing something? Is this really the way to go?

A lot of unneeded code for me...

Upvotes: 1

Views: 1653

Answers (3)

daxim
daxim

Reputation: 39158

The docs say that it raises exceptions:

If make_path or remove_tree encounter an error, a diagnostic message will be printed to STDERR via carp (for non-fatal errors), or via croak (for fatal errors).

That enabled us to use standard exception handling at least for the errors marked fatal.

use Try::Tiny;
try {
    … remove_tree …
} catch {
    warn "remove_tree failed: $_";
};

The warnings can be fatalised somehow, too, but I can't of anything decent right now except aliasing File::Path::_carp to File::Path::_croak.

Upvotes: 1

brian d foy
brian d foy

Reputation: 132858

I remove one path at a time then check if it is still there afterward:

 foreach my $path ( @paths ) {
      my $rc = remove_tree( $path, { ... } );
      die ... if -e $path;
      }

As Dancrumb said, you can't trust the return value.

Upvotes: 1

Dancrumb
Dancrumb

Reputation: 27549

remove_tree returns the number of files successfully deleted, so it needs another method of reporting an error than a return value. Bear in mind that a number of files may have been deleted before an error is encountered, so you can't rely on the returned value being 0 as indicating an error.

Whether this is the way to go for reporting errors is a matter of taste. From the docs themselves:

NOTE: The following error handling mechanism is considered experimental and is subject to change > pending feedback from users.

Upvotes: 3

Related Questions