Subject: | Not safe against exceptions |
Cwd::Guard and File::pushd have an advantage over File::cd --- they are safe against exceptions, that is, the chdir back to the original directory is done even if an exception happens. Compare the following examples:
#!/usr/bin/perl
use strict;
use warnings;
use Cwd::Guard 'cwd_guard';
use Cwd 'getcwd';
use Test::More 'no_plan';
my $orig = getcwd;
eval {
my $guard = cwd_guard '/tmp';
die;
}; warn $@ if $@;
is getcwd, $orig;
__END__
vs.
#!/usr/bin/perl
use strict;
use warnings;
use File::cd;
use Cwd 'getcwd';
use Test::More 'no_plan';
my $orig = getcwd;
eval {
cd '/tmp' => sub {
die;
};
}; warn $@ if $@;
is getcwd, $orig;
__END__
Maybe the difference should just be documented. I think it would also be possible to "fix" File::cd: calling $func should happen in an eval block, so exceptions can be trapped and re-thrown after doing the chdir back.