Something about this raises the "X/Y problem" hackles and makes me want to mumble something about using File::Spec and splitdir to break things up into a list of directory components instead (or Path::Tiny and doing . . . something).
definitely x/y, look at the post history
Comment on Re^2: How to remove everything after last occurrence of a string?