use strict; use warnings; use File::Spec (); foreach ( '/rootdir/sub1/sub2/sub3/sub4/', '/rootdir/sub1/sub2/sub3/sub4', '/rootdir/', '/rootdir', '/', 'C:\\', 'reldir/sub1/', 'reldir/sub1', 'reldir/', 'reldir', ) { my $path = $_; print("$path\n"); my ($vol, $dirs) = File::Spec->splitpath($path, 1); $dirs = File::Spec->canonpath($dirs); my @dirs = File::Spec->splitdir($dirs); pop(@dirs); $dirs = File::Spec->catdir(@dirs); $path = File::Spec->catpath($vol, $dirs, ''); print(" -> $path\n"); }