views:

333

answers:

2

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?

A: 

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

Quai
+8  A: 

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 );
DVK
Don't forget splitdir. A more elegant way to work with paths is Path::Class available from CPAN.
Schwern
@Schwern - I don't feel comfortable recommending Path::Class as I never used it myself... but I saw recommendations for it elsewhere on SO so I'll check it out. Good point about splitdir - though I'm afraid if I keep going the answer will turn into copy/paste of the POD :)
DVK
Path::Class is great, much easier to use than the alternatives.
singingfish
@singingfish - it does look fairly easy from surface examination, but to be honest File::Spec is IMHO easy enough to not require a simpler alternative, at least for any tasks I ever needed. But I like Path::Class APIss... clean and readable.
DVK
I am used to `File::Spec` but `Path::Class` is very good.
Sinan Ünür