File Coverage

blib/lib/Acme/CPANModules/TemporaryChdir.pm
Criterion Covered Total %
statement 3 3 100.0
branch n/a
condition n/a
subroutine 1 1 100.0
pod n/a
total 4 4 100.0


line stmt bran cond sub pod time code
1             package Acme::CPANModules::TemporaryChdir;
2              
3 1     1   355546 use strict;
  1         3  
  1         160  
4              
5             our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
6             our $DATE = '2023-12-15'; # DATE
7             our $DIST = 'Acme-CPANModules-TemporaryChdir'; # DIST
8             our $VERSION = '0.001'; # VERSION
9              
10             our $LIST = {
11             summary => 'List of modules to change directory temporarily',
12             description => <<'MARKDOWN',
13              
14             Changing directory can be tricky if you are doing it in a transaction or inside
15             a routine where you need to restore the previous working directory whether your
16             main action succeeds or not. Forgetting doing it and it will cause unexpected
17             behavior for the user calling your code.
18              
19             Restoring previous directory can be as simple as:
20              
21             use Cwd qw(getcwd);
22              
23             my $prevcwd = getcwd();
24             eval {
25             # do some stuffs that might die ...
26             };
27             # check success status ...
28             chdir $prevcwd or die "Can't chdir back to '$prevcwd': $!";
29              
30             but it can get tedious. Some modules can help. These modules employ one of
31             several mechanisms provided by Perl:
32              
33             1) Tied scalar, where reading from the scalar retrieves the current working
34             directory and writing to it changes the working directory. The user can set the
35             magic variable locally and have Perl restore the old value. Modules that use
36             this technique include: .
37              
38             2) An object, where its constructor records the current working directory and
39             its DESTROY restores the previously recorded working directory. The user can
40             create a lexically scoped object that can change directory but restores the
41             previous working directory when the object goes out of scope. Modules that use
42             this technique include: and .
43              
44             MARKDOWN
45             entries => [
46             {
47             module => 'File::chdir',
48             },
49             {
50             module => 'File::pushd',
51             },
52             {
53             module => 'Dir::TempChdir',
54             },
55             ],
56             };
57              
58             1;
59             # ABSTRACT: List of modules to change directory temporarily
60              
61             __END__