...或者...如果您不想依赖外部模块,您可以使用单行正则表达式替换来做到这一点:
(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.