perl脚本之目录

来源:

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

 

http://stackoverflow.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.

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

or

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

or

1 use Cwd qw( abs_path );
2 use Path::Class qw( file );
3 say file(abs_path($0))->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:

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

Or abs_path without an argument:

1 use Cwd qw();
2 my $path =Cwd::abs_path();
3 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:

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

See the File::Basename docs for more details.

 

3)

You could use FindBin:

1 use FindBin '$RealBin'; #推荐
2 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. 

posted @ 2016-08-05 17:12  醉游  阅读(647)  评论(0编辑  收藏  举报