0

我使用 perl 并在目录中保存了一个文件,如下所示:

/root/dir_1/dir_2/dir_3/dir_4/perl_file.pl

我试图从 perl 文件本身中做的是获取/root ... dir_4/or的字符串,dir_4/然后我可以使用它来创建另一个目录(我可以使用一个特定的模式来创建新目录)。

我一直在查看 File::Copy 和 File::Basename ,它们似乎需要您指定路径,但我希望我的路径可以根据运行的文件而变化。这看起来很简单,可能我只是忽略了一些东西,但这可能吗?

在伪代码中,我正在寻找类似的东西my $dir = UpOneDirectory(thisperlfile) or FilePath(thisperlfile)

4

3 回答 3

5
use FindBin qw( $RealBin );
say $RealBin;
于 2013-10-31T20:31:25.680 回答
1
use File::Basename;
use Cwd qw( abs_path );

my $dir = dirname(abs_path($0));
于 2013-10-31T20:33:40.227 回答
0

...或者...如果您不想依赖外部模块,您可以使用单行正则表达式替换来做到这一点:

(my $me = $0) =~ s#(^/.*?)/?[^/]*$#\1#;

这将分配一个字符串值$me,表示包含当前脚本的目录的路径。

这是它的工作原理。$0 包含当前执行脚本的路径。我们想把它赋值给,$me但我们也想用正则表达式替换来操作它,所以我们把赋值放在括号内(注意,“my”声明也必须放在括号内(否则 perl 将 barf)。

The regex matches the initial '/' followed by all characters up to the final '/' and then all non '/' characters to the end of the string (note: the regex is anchored on both ends using '^' and '$'). A grouping set is then used to substitute everything up to (but not including) the final '/' as the new string value. IOW: the directory component of the path.

Also note that all this extra fluff is simply to deal with the case where a file resides in the root directory and we want the result to actually be '/' (instead of ''). If we didn't need to cover this case, the regex could be much simpler, like so:

(my $me = $0) =~ s#/[^/]*$##; # DON'T USE THIS ONE  (Use the above example instead)

...but that doesn't cover all the bases.

于 2013-11-01T19:53:57.943 回答