All this does is create a tied scalar that when it goes out of scope returns you to your original working directory. (Or another of your choice.) Very handy if you want to move around the file-system in a function, but be where you started when you are done. Like this:
sub some_func { my $saveDir = new PreserveWD; # Do stuff }
package PreserveWD; use strict 'vars'; use Carp; use Cwd; sub back { my $self = shift; chdir($$self) or confess("Cannot chdir to $$self: $!"); } sub new { my $cwd; return tie $cwd, 'PreserveWD'; } sub TIESCALAR { my ($type, $dir) = @_; $dir ||= cwd(); return bless \$dir, $type; } *DESTROY = *back; 1;

Replies are listed 'Best First'.
RE: Preserve working directory
by merlyn (Sage) on Sep 30, 2000 at 04:46 UTC
    It looks like an unnecessary obfuscation. How about this instead...
    package PreserveWD; use strict; use Cwd qw(cwd); sub new { my $class = shift; my $self = cwd; bless \$self, $class; } sub DESTROY { chdir ${+shift) or die "Cannot restore directory\n"; }
    I think this is the model that SelectSaver uses. Yup. Similar code.

    -- Randal L. Schwartz, Perl hacker

      my $class = shit;
      Actually, your class is nice. :^) (Yes, I know I'm a bit late to the party. This was just too good to pass up anyway.)

      Makeshifts last the longest.