読者です 読者をやめる 読者になる 読者になる

Perl - File::pushd

File::pushd が

{
    $dir = pushd "/usr/local";
    ...
}

より

pushd "/usr/local" => sub {
    ...
};

みたいにかけた方がかっこいいと思ったので書いてみた。

#!/usr/bin/env perl
use strict;
use warnings;
use Cwd qw(cwd);

sub pushd {
    if (@_ == 1) {
        my $target = shift;
        my $orig   = cwd;
        chdir $target or die "chdir $target: $!";
        bless { orig => $orig }, "_Pushd";
    }
    elsif (@_ == 2) {
        my ($target, $cb) = @_;
        my $dir = pushd($target);
        $cb->();
    }
}
sub _Pushd::DESTROY {
    my $self = shift;
    chdir $self->{orig} or warn "chdir $self->{orig}: $!";
}

warn cwd;

pushd "/usr/local" => sub {
    warn cwd;
};

warn cwd;
__END__
> perl pushd.pl
/Users/skaji at pushd.pl line 24.
/usr/local at pushd.pl line 27.
/Users/skaji at pushd.pl line 30.