A Variable::Magic solution:
use Cwd qw( getcwd );
use Variable::Magic qw( cast wizard );
my $wiz = wizard(
get => sub {
${ $_[0] } = getcwd();
},
set => sub {
chdir( ${ $_[0] } )
or die( "chdir `${ $_[0] }`: $!" );
},
);
cast my $CD, $wiz;
With an alias:
use experimental qw( refaliasing declared_refs );
use Cwd qw( getcwd );
use Variable::Magic qw( cast wizard );
my $wiz = wizard(
get => sub {
my \$sv = shift;
$sv = getcwd();
},
set => sub {
my \$sv = shift;
chdir( $sv )
or die( "chdir `$sv`: $!" );
},
);
cast my $CD, $wiz;