I need to construct a file path inside a Perl script. Which path separator should I use to allow my script to work on both Windows and Unix?
Keep in mind that Windows needs a drive letter.
I need to construct a file path inside a Perl script. Which path separator should I use to allow my script to work on both Windows and Unix?
Keep in mind that Windows needs a drive letter.
Q:Which path separator should I use to allow my script to work on both Windows and Unix?
A: /.
Explanation: Windows can work similarly to Unix with / as path separator. (Mac OS uses : as a path separator instead of /). The File::Spec modules can also help. use File::Spec::Functions; chdir(updir()); # go up one directory $file = catfile(curdir(), 'temp', 'file.txt'); # on Unix and Win32, './temp/file.txt' # on Mac OS, ':temp:file.txt' # on VMS, '[.temp]file.txt' Source: http://www.xav.com/perl/lib/Pod/perlport.html
You want File::Spec. There are specific versions for Unix, Win32, and MacOS as well others.
It sounds like you are using path separator to mean the character between directory/file name components. But just in case you meant the other meaning:
Some things (notably environment variables like MANPATH or PERL5LIB) take a list of file or directory names, separated by a path separator character. Perl's Config module portably supplies such a character as $Config::Config{'path_sep'}.
You want File::Spec's catpath
:
catpath() Takes volume, directory and file portions and returns an entire path. Under Unix, $volume is ignored, and directory and file are concatenated. A '/' is inserted if need be. On other OSes, $volume is significant. $full_path = File::Spec->catpath( $volume, $directory, $file );
If you find File::Spec cumbersome, as I do, try Path::Class. It gives you directory and file objects to work with rather than having to call long winded File::Spec class methods on strings.