perl脚本之目录

时间:2023-03-10 01:12:02
perl脚本之目录

来源:

http://www.cnblogs.com/itech/archive/2013/02/20/2919204.html

http://*.com/questions/5703705/print-current-directory-using-perl?rq=1

1)

The following get the script's directory, which is not the same as the current directory. It's not clear which one you want.

 use Cwd qw( abs_path ); #推荐
use File::Basename qw( dirname );  #推荐 my $flk = abs_path($);  #F:/EclipseTest2/a/test1.pl
my $flk2 = dirname($flk); #F:/EclipseTest2/a say $flk2; #必须有use v5.10; 才能用say
 

or

 use Path::Class qw( file );    #我的系统上没有Path::Class模块。需要通过ppm安装一下就有了。本人不推荐用这个,因为产生的都是windows样式的分隔符
say file($)->absolute->dir; #结果 F:\EclipseTest2\a (windows样式的分隔符)

or

 use Cwd qw( abs_path );
use Path::Class qw( file );
say file(abs_path($))->dir; #结果 F:\EclipseTest2\a(windows样式的分隔符)

The middle one handles symlinks different than the other two, I believe. ?

2)

To get the current working directory (pwd on many systems), you could use cwd() instead of abs_path:

 use Cwd qw();
my $path =Cwd::cwd();
print "$path\n"; #结果 F:/EclipseTest2/a

Or abs_path without an argument:

 use Cwd qw();
my $path =Cwd::abs_path();
print "$path\n"; #结果 F:/EclipseTest2/a

See the Cwd docs for details.

To get the directory your perl file is in from outside of the directory:

 use File::Basename qw();
my($name, $path, $suffix)=File::Basename::fileparse($);
print "$path\n"; #F:/EclipseTest2/a/ 多一个/ 其实$name为test1.pl $suffix为

See the File::Basename docs for more details.

3)

You could use FindBin:

 use FindBin '$RealBin'; #推荐
print "$RealBin\n"; #F:/EclipseTest2/a FindBin sets both $Bin and $RealBin to the current directory.
FindBin is a standard module that is installed when you install Perl.