【问题标题】:Perl difference between 2 paths2条路径之间的Perl区别
【发布时间】:2017-06-26 02:55:29
【问题描述】:

如何获得两条路径之间的差异?

我们有 $src 变量,它被定义为基本路径,我们将修改后的列表放入 FilesList.txt。

作为

$src = "C:\\Users\\Desktop\\Perl\\Index"
$_ = "C:\Users\Desktop\Perl\Index\CC\Login.jsp";

现在,我们如何获得“CC\Login.jsp”值,我正在使用下面的代码,但我们没有得到预期的输出。请帮忙。

$src="C:\\Users\\Desktop\\Perl\\Index";
open IN, "FilesList.txt";  
while(<IN>)
{
    chomp($_);
    $final=$_;
    $final =~ s/\$src//;
    print "\nSubvalue is ---$final \n";
}

【问题讨论】:

  • 试试s/^\Q$src\\//
  • $final =~ s/$src//; 而不是$final =~ s/\$src//;去掉$src之前的斜线;

标签: windows perl filepath relative-path


【解决方案1】:

不要使用正则表达式模式来处理路径字符串。等效路径有多种不同的表示形式,并且字符串可能不匹配。正则表达式也不会注意路径分隔符,因此它不会更正基本路径上的尾随分隔符,并且它可能匹配部分路径步骤,如C:\Users\Desktop\Perl\Ind,留下ex\CC\Login.jsp,这显然是错误的

您需要来自File::Spec::Functionsabs2rel 函数

这样

use strict;
use warnings 'all';
use feature 'say';

use File::Spec::Functions 'abs2rel';

my $src = 'C:\Users\Desktop\Perl\Index';

for ( 'C:\Users\Desktop\Perl\Index\CC\Login.jsp' ) {

    say abs2rel($_, $src);
}

输出

CC\Login.jsp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 2018-06-17
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多