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

Ram picture Ram · May 24, 2010 · Viewed 15.3k times · Source

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?

Answer

DVK picture DVK · May 24, 2010

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 );