Lazer
Lazer

Reputation: 94850

How can I correct the path of a file to be OS specific in Perl?

Due to some messed up legacy code,

I have

$path = [OS specific base DIR name][hardcoded Linux file path]

So on Linux, it is something like

$path = /common/path/to/dir/pathtofile/name.extension

but on Windows it becomes this

$path = C:\path\to\dir\pathtofile/name.extension

Some of the code fails on Windows because it is expecting a \ while it gets a /.

Is there a Perl function that can help me here?

Something like

print "$path\n";
$path = <some function> $path;
print "$path\n";

C:\path\to\dir\pathtofile/name.extension
C:\path\to\dir\pathtofile\name.extension

Upvotes: 1

Views: 111

Answers (3)

Jander
Jander

Reputation: 5637

It sounds like you're getting the entire $path handed to you from somewhere else as one unit, rather than having the luxury of dealing with the pieces separately. In which case, I don't see a better answer than the ugly solution of replacing all slashes with backslashes if we're running under Windows.

The following should do what you need:

if ($^O =~ /^MSWin/) {
    $path =~ s{/}{\\}g;
}

EDIT: On second thought -- having taken a look at File::Spec, it looks like you want the canonpath function:

use File::Spec;
# ...
$path = File::Spec->canonpath($path);

Upvotes: 0

rafl
rafl

Reputation: 12341

The File::Spec family of modules exists exactly for that reason. You might want to consider using that instead of hardcoding unix paths.

use File::Spec::Functions 'catfile';

my $path = catfile($os_specific_base_dir, 'pathtofile', 'name.extension');

If you really need to hardcode unix paths somewhere, which really doesn't seem like a good idea, you should probably use File::Spec::Unix to split up the path into its components, and then use the File::Spec variant native to your target system to build put the components back together again.

Upvotes: 6

Jonathan Leffler
Jonathan Leffler

Reputation: 754050

Have you looked at the File::Spec core modules - and related ones?

Upvotes: 1

Related Questions