Files and Filesystems
File path components are separated with /
on Unix, with \ on Windows, and
with : on the old pre-Unix Macs.
Some systems support neither hard links (link) nor symbolic links (symlink, readlink, lstat). Some systems pay attention to
capitalization of filenames, some don’t, and some pay attention when
creating files but not when reading them. Different systems use
different character repertoires.
Here are some tips for writing portable file-manipulating Perl programs:
The
File::Basenamemodule, another platform-tolerant module bundled with Perl, splits a pathname into its components: the base filename, the full path to the directory, and the file suffix:use File::Basename; my $name = basename( $ARGV[0] ); my $dir = dirname( $ARGV[0] ); my( $base, $dir, $suffix ) = fileparse( $ARGV[0], qr/\.[^.]+\z/ );
The standard
File::Specmodules provide functions to move around a file system and put path components together properly. Don’t hardcode paths, but construct them:use File::Spec::Functions; chdir( updir() ); # go up one directory $file = catfile( curdir(), "temp", "file.txt" );
That last line reads in ./temp/file.txt on Unix and Windows or [.temp]file.txt on VMS, and stores the file’s contents in
$file.The
File::HomeDirmodule from CPAN locates special user directories by detecting your operating system and constructing the right paths for you.Use the
Path::ClassCPAN module for an object-oriented interface toFile::Specthat easily allows reading a path from one sort ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access