Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 764
Ram Avatar asked May 24 '10 13:05

Ram


People also ask

How do I get the directory path in Perl?

The dirname() method in Perl is used to get the directory of the folder name of a file.

How do I specify a file path in Perl?

You specify the pathname in the manner in which your operating system expects it, as shown in the following examples: open(MYFILE, "DISK5:[USER. PIERCE. NOVEL]") || die; # VMS open(MYFILE, "Drive:folder:file") || die; # Macintosh open(MYFILE, "/usr/pierce/novel") || die; # Unix.

What is the directory separator character?

Microsoft chose the backslash character ("\") as a directory separator, which looks similar to the slash character, though more modern version of Windows are slash-agnostic, allowing mixage of both types of slashes in a path.


2 Answers

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 );
like image 176
DVK Avatar answered Sep 19 '22 19:09

DVK


The accepted answer solves your real problem, but 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.

like image 27
ardnew Avatar answered Sep 16 '22 19:09

ardnew