What Perl module(s) do I use to obtain an absolute path (including filename) from a relative one on Windows?

Deadly 提交于 2020-01-14 09:21:07

问题


I can only imagine I'm not searching correctly; this seems like an obvious question to be asked here. My apologies if this is a duplicate.

I'm writing a Perl program that will take a filename as a command-line argument. I need to convert the filename (or the filename with a relative path attached) to an absolute path (specifically to work with Win32::OLE).

I tried using Cwd's 'abs_path', and that almost does what I want, but it returns it using a Unix-style path instead of a Win32 one.

Is there a module that will convert the path, or perhaps a better module to use in the first place?


回答1:


I use rel2abs from File::Spec. You have to be careful though: that might call getdcwd from Cwd, and it will assume that you want the current working directory for the current drive. If the file is on some other drive, you'll have to fix that up yourself or supply the second argument to set the base path.




回答2:


use File::Spec::Functions qw(rel2abs);
print rel2abs($ARGV[0]), "\n";



回答3:


my($foo) = abs_path($some_file);
$foo =~ s{/}{\\}g;

print "FOO: $foo\n";



回答4:


I use Cwd's abs_path and then use a regex to convert the slashes when I really need it done. But I've found that for most uses, Unix-style slashes work just fine. It's only for the occasional "pass a filename to that annoyingly limited program" that I end up needing to convert the slashes.

use Cwd 'abs_path';
my $path = abs_path($rel_path);

# and only if necessary...
$path =~ s'[/\\]+'\\'g;  # use Windows-style slashes
$path =~ s'^\\'\\\\';    # handle network path

But then.. I use a lot of network paths, with or without a mapped drive reference. Your mileage may vary.



来源:https://stackoverflow.com/questions/1527638/what-perl-modules-do-i-use-to-obtain-an-absolute-path-including-filename-fro

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