如何在Perl中获取目录(文件路径)分隔符?

时间:2022-11-09 23:22:44

In case of Java, we can get the path separator using

在Java的情况下,我们可以使用路径分隔符

System.getProperty("path.separator");

Is there a similar way in Perl? All I want to do is to find a dir, immediate sub directory. Say I am being given two arguments $a and $b; I am splitting the first one based on the path separator and joining it again except the last fragment and comparing with the second argument.

在Perl中有类似的方式吗?我想做的就是找到一个目录,直接子目录。说我有两个参数$ a和$ b;我基于路径分隔符拆分第一个并再次连接它,除了最后一个片段并与第二个参数进行比较。

The problem is my code has to be generic and for that I need to know whats the system dependent path separator is?

问题是我的代码必须是通用的,为此我需要知道系统相关的路径分隔符是什么?

3 个解决方案

#1


4  

The accepted answer solves your real problem, but if you really want to get the separator (using only perl core modules):

接受的答案解决了您的实际问题,但如果您真的想要获取分隔符(仅使用perl核心模块):

my $sep = File::Spec->catfile('', '');

This joins two empty file names with the current system's separator, leaving only the separator.

这会将两个空文件名与当前系统的分隔符连接起来,只留下分隔符。

#2


21  

You should not form file paths by hand - instead use File::Spec module:

您不应该手动形成文件路径 - 而是使用File :: Spec模块:

($volume, $directories,$file) = File::Spec->splitpath( $path );
@dirs = File::Spec->splitdir( $directories );
$path = File::Spec->catdir( @directories );
$path = File::Spec->catfile( @directories, $filename );

#3


8  

You can use the SL constant in File::Util.

您可以在File :: Util中使用SL常量。

#1


4  

The accepted answer solves your real problem, but if you really want to get the separator (using only perl core modules):

接受的答案解决了您的实际问题,但如果您真的想要获取分隔符(仅使用perl核心模块):

my $sep = File::Spec->catfile('', '');

This joins two empty file names with the current system's separator, leaving only the separator.

这会将两个空文件名与当前系统的分隔符连接起来,只留下分隔符。

#2


21  

You should not form file paths by hand - instead use File::Spec module:

您不应该手动形成文件路径 - 而是使用File :: Spec模块:

($volume, $directories,$file) = File::Spec->splitpath( $path );
@dirs = File::Spec->splitdir( $directories );
$path = File::Spec->catdir( @directories );
$path = File::Spec->catfile( @directories, $filename );

#3


8  

You can use the SL constant in File::Util.

您可以在File :: Util中使用SL常量。