A bit of defensive programming here will certainly help. You can use the core module File::Spec::Functions function canonpath to normalize your path to the canonical form for the operating system. The following code works under both Windows and Unix happily.
use strict;
use File::Spec::Functions;
use Data::Dumper; # for debugging purpose only
my $path = canonpath("../somedir/path/");
print "$path\n";
my @dirs = qw( ../dir/path1 ../dir/path2 );
my @canon_dirs = map { canonpath($_) } @dirs;
print Dumper(\@canon_dirs);
And the results when run under Solaris 2.8 -
../somedir/path
$VAR1 = [
'../dir/path1',
'../dir/path2'
];
and the same script run under Windows XP -
..\somedir\path
$VAR1 = [
'..\\dir\\path1',
'..\\dir\\path2'
];
And another word of advice - try to keep the directories and files in the Perl script relative to a particular root directory. And append the root directory in front of the relative path when openning files. This will keep the amount of work minimal when porting between different platforms.
use strict;
use File::Spec::Functions;
my %root = (
MSWin32 => "C:\\Data",
solaris => "/var/data",
);
my $ROOTDIR = $root{$^O} or die "Unknown platform";
my $file1 = canonpath("$ROOTDIR/data.txt");
print "$file1\n";
my $file2 = canonpath("$ROOTDIR/../input/data2.txt");
print "$file2\n";
And the result on Windows XP -
C:\Data\data.txt
C:\Data\..\input\data2.txt
the same script run on Solaris without modification -
/var/data/data.txt
/var/data/../input/data2.txt
|