File::cd - Easily and safely change directory
version 0.003
use 5.010; use File::cd; use Cwd qw(cwd); cd '/tmp' => sub { # output: /tmp say cwd; # do something in /tmp process_directory(); # we can also nest multiple cds cd '/home/foo' => sub { ... }; }; # back at original directory say cwd;
The global (and negative) effect of perl builtin function chdir is well known (see File::chdir's documentation for more details). And few modules have been created to solve this problem:
chdir
File::chdir, by David Golden.
File::pushd, also by David Golden.
Cwd::Guard, by Masahiro Nagano.
Unfortunately, I'm not a big fan of their interface. So this modules provides yet another way to change directory in perl.
Exports the function cd by default.
cd
Change directory to $dir, invoke the function reference $code inside that directory, and go back to original directory.
$dir
$code
The return value of this function is the value of the last expression in $code. Here's an example to utilize it:
# get a list of files contained in directory /home/example use File::Spec qw(catfile); my $destination = '/home/example'; my @files = cd $destination => sub { map { catfile $destination, $_ } glob '*' } # make sure to match the context! my $files = cd $destination => sub { [ map { catfile $destination, $_ } glob '*' ] }
Throws an exception when the directory $dir does not exist or is not a directory.
NOTE: This function is prototyped, which means the validity of supplied arguments are checked at compile time.
Ahmad Syaltut <syaltut at cpan.org>
This software is copyright (c) 2013 by Ahmad Syaltut.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
To install File::cd, copy and paste the appropriate command in to your terminal.
cpanm
cpanm File::cd
CPAN shell
perl -MCPAN -e shell install File::cd
For more information on module installation, please visit the detailed CPAN module installation guide.