1. Perl
  2. File operations
  3. Module
  4. File::Spec

Convert the file name to the file name in the OS of the execution environment

You could use File::Spec->catfile to create an OS-independent filename. This time, I will explain how to convert a certain file representation to the file name of the OS of the execution environment. When specifying a file name in a configuration file, etc., the file representation in Unix is often used.

# File representation on Unix
dir1/dir2/file.txt

Suppose you want to convert this Unix file representation to a Windows file representation on Windows. It's easy to do the following:

The splitdir method of File::Spec splits $unix_path into individual parts. Connect it with the catfile method. catfile will combine the decomposed filenames with \.

use File::Spec;
my $unix_path = 'dir1/dir2/file.txt';
my $windows_path = File::Spec->catfile(File::Spec->splitdir($unix_path));

Executable example

use strict;
use warnings;

use File::Spec;
my $unix_path = 'dir1/dir2/file.txt';
my $windows_path = File::Spec->catfile(File::Spec->splitdir($unix_path));

print "1. Convert to Windows file path\n";
print $windows_path, "\n";

Output result on Windows

1. Convert to Windows file path
dir1\dir2\file.txt

Related Informatrion