Perl中的Cwd模块
(2016-11-21 15:48:15)| 分类: Perl |
1.
这个模块提供了确定当前工作目录的路径名的功能。getcwd(或者另一个*cwd())对所有的代码可移植性好,所以被推荐使用。模块默认导出的函数有getcwd,cwd,fastcwd,fastgetcwd.
这些函数都不需要带参数,返回当前工作目录(Current Working Directory)的绝对路径。
cwd:
The cwd() is the most natural form for the current architecture. For most systems it is identical to `pwd` (but without the trailing line terminator).
fastcwd:
一个更危险的getcwd版本,但是更快;
可以料想到,chdir()或许会使你移出一个不能重新chdir()回的一个目录。如果fastcwd遇到一个问题,它将会返回undef,但是可能留你在一个不同的目录。对额外的完全性策略,如果一切似乎已经工作,fastcwd()将检测是不是留你在开始时相同的目录。如果目录改变了,它将会报错并die"Unstable directory path, current directory changed unexpectedly"。
fastgetcwd:
作为cwd的同义词被提供。
getdcwd:
Win32 系统提供了此函数,获得指定驱动下的当前工作目录,因为windows为每个驱动维护一个单独的当前工作目录。如果没有指定驱动的话,当前的驱动被假设。
cwd:
The cwd() is the most natural form for the current architecture. For most systems it is identical to `pwd` (but without the trailing line terminator).
fastcwd:
一个更危险的getcwd版本,但是更快;
可以料想到,chdir()或许会使你移出一个不能重新chdir()回的一个目录。如果fastcwd遇到一个问题,它将会返回undef,但是可能留你在一个不同的目录。对额外的完全性策略,如果一切似乎已经工作,fastcwd()将检测是不是留你在开始时相同的目录。如果目录改变了,它将会报错并die"Unstable directory path, current directory changed unexpectedly"。
fastgetcwd:
作为cwd的同义词被提供。
getdcwd:
Win32 系统提供了此函数,获得指定驱动下的当前工作目录,因为windows为每个驱动维护一个单独的当前工作目录。如果没有指定驱动的话,当前的驱动被假设。
use Cwd 'abs_path';
use Cwd qw(abs_path realpath fast_abs_path);
abs_path:
用和getcwd一样的算法,
my $abs_path = abs_path($file);
realpath:
abs_path的同义词;
fast_abs_path:
危险的,但更快;
2.$ENV{PWD}
如果想要$ENV{PWD}保持更新,就要导入Cwd的chdir()函数来重写内置(built-in)的chdir().
eg:
$cur_path = $ENV{PWD};
print $cur_path."\n";
chdir("/root");#这里的chdir是Perl中内置的chdir,不会改变$ENV{PWD}的值
$cur_path =$ENV{PWD};
print $cur_path."\n";
output:
/root/test
/root/test
use Cwd 'chdir';
$cur_path =$ENV{PWD};
print $cur_path."\n";
chdir("/");#导入了Cwd中的chdir,所以这里会改变$ENV{PWD}的值
$cur_path =$ENV{PWD};
print $cur_path."\n";
output:
/root/test
/

加载中…