Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I construct OS-independent file paths in Perl including an optional Windows drive letter?

Tags:

path

windows

perl

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.

like image 282
Sergey Stadnik Avatar asked Nov 30 '09 06:11

Sergey Stadnik


3 Answers

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 );
like image 184
brian d foy Avatar answered Nov 07 '22 19:11

brian d foy


You want File::Spec. There are specific versions for Unix, Win32, and MacOS as well others.

like image 21
s1n Avatar answered Nov 07 '22 19:11

s1n


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.

like image 33
Schwern Avatar answered Nov 07 '22 21:11

Schwern