How about this OO approach: #!/usr/bin/perl -w
use strict;
package MyCwd;
use Cwd;
sub cd
{
warn "must assign to something!\n" if !defined(wantarray);
my $class = shift;
my $new_dir = shift;
my $self = cwd;
chdir $new_dir;
bless(\$self, $class);
}
sub DESTROY
{
my $self = shift;
chdir $$self;
}
"that's it!";
And then you'd use it like this: package main;
use MyCwd;
use Cwd;
print cwd, "\n";
if (1)
{
my $cwd = MyCwd->cd('..');
{
my $cwd = MyCwd->cd('..');
print cwd, "\n";
]
print cwd, "\n";
}
print cwd, "\n";
Every time you construct a new MyCwd, it remembers where you were. When it goes out of scope, it changes back.
update: Separated demo code. Added check for call in void context. |