Take the 2-minute tour ×

My application accepts a number of paths from users that may or may not have terminated those paths with a backslash. I would like to ensure that all paths are terminated with a backslash () so that I can append filenames to them for performing other various operations. I've dug through a lot of questions here and haven't been able to find a solution so I hacked together the following:

    foreach my $path (@Path) {
      my $char = chop($path);
      if ($char ne '\\') {
        $path = $path . $char . '\\';
      } else {
        $path = $path . '\\';

This is probably a pretty terrible way of doing it, but it works. Can anyone provide me a regex alternative?

share|improve this question
You should consider using a module for paths, such as File::Spec –  TLP Sep 23 '13 at 18:52
add comment

2 Answers

up vote 1 down vote accepted
$path =~ s/(?<!\\)$/\\/;

(?<!\\) is a negative lookbehind which will cause the match to fail if the previous character is not a backslash, and the $ is an end of string anchor. So this regex will fail to match anything if the last character is a backslash, or it will match after the last character in the string if that character is not a backslash. We then use a backslash as the replacement so if the regex matched we append a backslash to the end.

share|improve this answer
s/\\?$/\\/ will do the same thing. –  TLP Sep 23 '13 at 18:59
Worked like a charm. Greatly appreciated. –  user2808297 Sep 23 '13 at 19:19
@user2808297 What convinced you? The part where its less easy, less safe or less portable? –  TLP Sep 23 '13 at 21:48
add comment

Use File::Spec to build your paths. It is easier, and safer and more portable.

use File::Spec;
for my $path (@Path) {
    $path = File::Spec->catfile($path, "foo", "bar");
    # $path = "$path\foo\bar"  -- regardless of previous line ending
share|improve this answer
add comment

Your Answer


