Using Perl on Windows, how can I ensure I get the path in the correct case following a chdir?

笑着哭i 提交于 2019-12-07 07:20:53

问题


Consider the following code:

print cwd . "\n";
$str= "../source"; # note the lower case 's'    
chdir($str);
print cwd . "\n";

If my current directory is c:\parentdir\Source (note the capital 'S'), the output of this will be:

c:/parentdir/Source
c:/parentdir/source

This causes problems in a subroutine of mine that cares about the correct case of folder names. $str is passed in to my subroutine, so I can't know ahead of time whether it has the correct case. How do I determine the case-correct name of a path that matches $str?

More detail here:

  • I realize that ../source is a pathological example, but it serves to illustrate the problem. It occurs even if $str is requesting a folder other than the current one.
  • I have tried numerous options, including rel2abs, a glob search on $str, and others, but they all seem to return "source" instead of "Source".
  • I could search $str/.. for all directories, convert them all to absolute paths and compare them to an absolute path version of $str, but that seems like a hack. I was hoping for something more elegant.

回答1:


#!/usr/bin/perl

use warnings; use strict;
use Cwd;
use File::Spec::Functions qw( canonpath );
use Win32;

print canonpath( cwd ), "\n";

chdir '../source';

print canonpath( cwd ), "\n";

print canonpath( Win32::GetLongPathName( cwd ) ), "\n";
C:\DOCUME~1\...\LOCALS~1\Temp\t\Source> t
C:\DOCUME~1\...\LOCALS~1\Temp\t\Source
C:\DOCUME~1\...\LOCALS~1\Temp\t\source
C:\Documents and Settings\...\Local Settings\Temp\t\Source


来源:https://stackoverflow.com/questions/7995113/using-perl-on-windows-how-can-i-ensure-i-get-the-path-in-the-correct-case-follo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!