my $key = "C:\\abc\\dfg"; my @example = ("C:\\abc\\dfg\\axy", "C:\\abc\\dfg\\#\@\$#\@\$\@\\hwllo"); use File::Spec::Functions qw(abs2rel); foreach (@example) { my $rel = abs2rel($_, $key); printf "in: %s\nout: %s\n\n", $_, $rel; } #### in: C:\abc\dfg\axy out: axy in: C:\abc\dfg\#@$#@$@\hwllo out: #@$#@$@\hwllo #### # modified source use File::Spec::Functions qw(abs2rel splitdir); foreach (@example) { my $rel = abs2rel($_, $key); my($topdir) = splitdir($rel); printf "in: %s\nout: %s\ntop directory: %s\n\n", $_, $rel, $topdir; } #### in: C:\abc\dfg\axy out: axy top directory: axy in: C:\abc\dfg\#@$#@$@\hwllo out: #@$#@$@\hwllo top directory: #@$#@$@