develooper Front page | perl.fwp | Postings from November 2001

pop @CWD -> chdir(File::Spec->updir)

Michael G Schwern
November 26, 2001 16:50
pop @CWD -> chdir(File::Spec->updir)
Message ID:
I think this is pretty fun:

    #!/usr/bin/perl -wl
    use File::chdir;

        local $CWD;
        do {
            print $CWD;
        } while pop @CWD;

    print $CWD;

now you can write polite subroutines that don't leave you in some
funny directory, even if they die:

    sub foo {
        local $CWD = 'somewhere/else';

want to change your parent directory?

    $CWD[-2] = 'something_else';

or how about a zsh style cd?

    $CWD =~ s/foo/bar/;

tired of mucking with File::Spec->catdir?

    push @CWD, 'some', 'other', 'dir';

How about a safe File::Find?  Even if this gets confused you won't
wind up dumped in some random directory.

    use File::chdir;

    sub traverse_dir {
        my($dir, $callback) = @_;

        local $CWD = $dir;
        print "$dir";
        opendir CWD, $CWD;
        foreach my $dir (grep !/^\.{1,2}$/, readdir CWD) {
            local $_ = $dir;
            traverse_dir($dir, $callback) if -d $dir;
        closedir CWD;
    traverse_dir('/some/directory', sub { print "$_\n" });

    # Right back where we started.
    print $CWD;

Available at
This version won't be on CPAN for another week since it deletes some
old functionality.  Giving people a chance to prepare for the new


Michael G. Schwern   <>
Perl Quality Assurance	    <>	       Kwalitee Is Job One
Your average appeasement engineer is about as clued-up on computers as
the average computer "hacker" is about B.O.
	-- BOFH Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About