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

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

From:
Michael G Schwern
Date:
November 26, 2001 16:50
Subject:
pop @CWD -> chdir(File::Spec->updir)
Message ID:
20011126195041.A7982@blackrider
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;
            $callback->($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 http://ww.pobox.com/~schwern/src/File-chdir-0.05.tar.gz.
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
interface.

-- 

Michael G. Schwern   <schwern@pobox.com>    http://www.pobox.com/~schwern/
Perl Quality Assurance	    <perl-qa@perl.org>	       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



nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About