David W.
David W.

Reputation: 107090

Perl Handling Directory Separators

I really should know this, but I've worked mainly with Linux, Mac OS X and Windows which all use the forward slash (/) as a directory separator (Windows can use either \ or /.).

That means when I normally write programs in Perl, I can simply use / as the directory separator and everything is fine. However, I know that File::Spec is suppose to allow for the portability of file separators (whatever that means).

If I am on a system that does not use forward slashes as a directory separator, I understand that users expect to be able to input files with the default separators and see output with the default separators. (For example, a Windows user will input and expect output to be C:\Users\smith\Documents and not C:/Users/smith/Documents), but what does Perl do internally?

Can I, despite what the platform may use as a directory separator, simply use forward slashes when I'm dealing with files internally. For example, I have a directory $dir and a file called $file, and I want to open the file. Can I simply say $dir/file, or do I have to use File::Spec to concat the name for me?

In fact, do Perl programs require forward slashes in directory names? I'm writing a module, and will be delivering file names to the calling program. Should I give the file as /foo/bar/fubar or if the system uses colons like the early Macintosh OS, say :foo:bar:fubar?

Upvotes: 9

Views: 1745

Answers (1)

mob
mob

Reputation: 118695

perlport says almost everything there is to say about this subject. That said, systems that can not accept / as the path separator are rare, and you might not have that much to gain from using File::Spec faithfully everywhere. But also be careful to distinguish internal and external uses of the directory separator. For example, this will work on Windows:

open my $fh, '<', 'C:/some/directory/to/some/file';

but this might not, because it needs to be processed by the Windows shell:

system("C:/some/program.exe C:/some/program/argument.txt");

Upvotes: 7

Related Questions