The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

File::chdir - a more sensible chdir()

SYNOPSIS

  use File::chdir;
  use Cwd;
  
  chdir("/foo/bar");     # now in /foo/bar
  {
      my $old_dir = chdir("/moo/baz");  # now in /moo/baz
      ...
  }

  # still in /foo/bar!

DESCRIPTION

Perl's chdir() has the unfortunate problem of being very, very, very global. If any part of your program calls chdir() or if any library you use calls chdir(), it changes the current working directory for the whole program.

This sucks.

File::chdir gives you two alternatives. They can be safely intermixed.

$CWD

Alternatively, you can use the $CWD variable instead of chdir().

    use File::chdir;
    $CWD = $dir;  # just like chdir($dir)!

It can be localized, and it does the right thing.

    $CWD = "/foo";      # it's /foo out here.
    {
        local $CWD = "/bar";  # /bar in here
    }
    # still /foo out here!

chdir()

File::chdir gives you a dynamically-scoped chdir(). Your chdir() calls will have effect as long as you're in the current block. Once you exit, you'll rever back to the old directory.

The problem is, this requires special syntax.

    chdir($dir);

This acts just like perl's chdir().

   { my $old_dir = chdir($dir); }

This one is scoped to the current block.

EVERYWHERE!

If you want this magic chdir() to completely replace Perl's regular chdir() across all packages, you can do this:

    use File::chdir ':EVERYWHERE';

Heh, have fun!

SEE ALSO

Michael G Schwern <schwern@pobox.com>

NOTES

This module requires perl 5.6.1

HISTORY

See the "local chdir" thread on p5p.