1. Perl
  2. Module
  3. here

File::Spec - Create OS - independent file name

The File::Spec module allows you to do portable processing on filenames. For example, you can create a file name using an OS-specific file name delimiter.

# Load module
use File::Spec;

The File::Spec method is implemented as a class method and is called in the following format.

# Class method call



Use catfile to create filenames from individual parts. $file is "xxx\yyy\zzz" for Windows and "xxx/yyy/zzz" for Unix. OS-specific delimiters are used to create filenames.

# Create file name
my $file = File::Spec->catfile('xxx', 'yyy', 'zzz');

It can also be used to concatenate directory names and file names. You do not need to be aware of the presence of delimiters such as "/" and "\" at the end of the directory name.

# Concatenate directory name and file name
my $dir = 'xxx/yyy /';
my $file = 'zzz';

my $file_abs = File::Spec->catfile($dir, $file);


Use splitdir to split the filename into individual parts. @parts becomes ('xxx','yyy','zzz').

# Decompose file name
my @parts = File::Spec->splitdir('xxx/yyy/zzz');

File::Spec Technique

You may want to create a file name with the delimiter "/" even on Windows. To achieve this, use File::Spec::Unix instead of File::Spec.

# Concatenate file names with "/"
use File::Spec::Unix;
my $file = File::Spec::Unix->catfile('xxx', 'yyy', 'zzz');


The standard open function etc. works correctly with both the Unix delimiter "/" and the Windows delimiter "\". So if you just want to open a file, you don't need to convert Unix delimiters to Windows delimiters.

Related articles

Related Informatrion