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
?
fileparse - split a pathname into pieces. basename - extract just the filename from a path. dirname - extract just the directory from a path.
use File::Spec; ... my $rel_path = 'myfile. txt'; my $abs_path = File::Spec->rel2abs( $rel_path ) ; ... and if you actually need to search through your directories for that file, there's File::Find... but I would go with shell find / -name myfile. txt -print command probably.
The directory separator character separates subdirectories within the nested directory hierarchy. An optional filename. The directory separator character separates the file path and the filename.
To open a file that's in another directory, you must use a pathname. The pathname describes the path that Perl must take to find the file on your system. You specify the pathname in the manner in which your operating system expects it, as shown in the following examples: open(MYFILE, "DISK5:[USER.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With