【问题标题】:Substitute strings (filename) in given directory in Perl在 Perl 的给定目录中替换字符串(文件名)
【发布时间】:2021-09-20 13:11:05
【问题描述】:

我有一个标量变量中包含文件名的完整目录路径。我想从文件名(ab%ABpeterfra)中提取某种字符串。

下面的脚本:

use strict; use warnings;

my $file = "/this/is/my/directory/ab%ABpeterfra";
print "file:$file\n";

my @array = split('%', $file); print $array[1]."\n"; 

my $final = substr($array[1], 2);

print "final:$final\n"; #peterfra

在这里我得到了想要的结果,即 peterfra。

但是有什么方法可以使用 Perl 替换并获得相同的结果或更好的方法来解决问题?

【问题讨论】:

    标签: perl substitution


    【解决方案1】:

    使用替换运算符的等价物是

    my $final = $file =~ s/^[^%]*%..//sr;   # $file if no match
    

    但比起拿走我不想要的东西,我更愿意找到我想要的东西。

    使用匹配运算符的等价物是

    my ($final) = $file =~ /%..(.*)/s;      # undef if no match
    

    【讨论】:

    • 当有两个%时,这些与原始代码略有不同。
    猜你喜欢
    • 1970-01-01
    • 2020-07-23
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 2021-12-02
    • 1970-01-01
    相关资源
    最近更新 更多