views:

58

answers:

3

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
+1  A: 

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

Jonathan Leffler
+6  A: 

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.

rafl
yes, I know about catfile and how it can be used to generate OS specific names. I have used that before. In this case, I have no control over the names that I get. I get `$path` set from somewhere already. I can only change it after I get it (as I have mentioned in the question).
Lazer
Right. That's why I mentioned an alternative for handling that in my answer as well.
rafl
A: 

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);
Jander