Ram
Ram

Reputation: 3114

How can I get the directory (file path) separator in Perl?

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

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.

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

Upvotes: 19

Views: 17175

Answers (4)

ardnew
ardnew

Reputation: 2086

If you really want to get the separator (using only Perl core modules):

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

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

Upvotes: 13

algn2
algn2

Reputation: 41

Before File::Spec, this is what I used. It still works today and it worked on very old perls on every Unix-like and Windows platforms that I've ever encountered.

Basically, the idea is to ask perl what it uses as directory separator char:

$dirSep = ( $ENV{"PATH"} =~ m/;[a-z]:\\/i ) ? '\\' : '/' ; 
print $dirSep;

Upvotes: 1

DVK
DVK

Reputation: 129403

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

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

Upvotes: 26

Quai
Quai

Reputation: 303

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

Upvotes: 10

Related Questions