2

我的应用程序接受来自用户的许多路径,这些路径可能会或可能不会用反斜杠终止这些路径。我想确保所有路径都以反斜杠 () 终止,以便我可以将文件名附加到它们以执行其他各种操作。我在这里挖掘了很多问题,但无法找到解决方案,所以我将以下内容拼凑在一起:

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

这可能是一种非常糟糕的方式,但它确实有效。谁能给我一个正则表达式替代品?

4

2 回答 2

8

用于File::Spec构建您的路径。它更容易、更安全、更便携。

use File::Spec;
for my $path (@Path) {
    $path = File::Spec->catfile($path, "foo", "bar");
    # $path = "$path\foo\bar"  -- regardless of previous line ending
}
于 2013-09-23T18:57:58.647 回答
1
$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.

于 2013-09-23T18:45:48.747 回答