November 26, 2014

Perl long paths issue in Windows environment

Windows allows to create file paths greater than Windows MAX_PATH value (260 characters). Perl native functions cannot work correctly with such files. For example, function rmtree() is not able to delete such files.

There is a module which solves the issue in Perl - Win32-LongPath. It provides functions to access long paths and Unicode in the Windows environment.

It could be easily installed for Perl 5.18. You need just search module with the Win32-LongPath name inside Perl package manager. If it is necessary to install the module for older versions of Perl, e.g. 5.8, you need to use the following command:

ppm install http://www.bribes.org/perl/ppm/Win32-LongPath.ppd

Below example of  implementation rmtree using Win32-LongPath functions. Function rmtreeWin() receives full file name as a parameter, identify whether it directory of file and tries to delete it. Note that Wind32-LongPath functions rmdirL and unlinkL cannot delete read-only files/dirs, so we need to change its attributes first.

use Win32::LongPath;

sub rmtreeWin() {
    chmod 0777, $_[0];

    if (-d) {
        rmdirL $_[0] or die "unable to remove directory $_[0] ($^E)";
    }
    else {
        unlinkL $_[0] or die "unable to delete file $_[0] ($^E)";
    }
}