我是perl脚本编程的新手.有人可以告诉我如何找到字符串中的最后一个子字符串索引,该字符串在字符串中重复多次.
实际上我想从给定路径中提取文件名
$outFile = "C:\\AOTITS\\BackOffice\\CSVFiles\\test.txt";
Run Code Online (Sandbox Code Playgroud)
如果我能找到'\'的最后一个字符串,我会使用substr函数提取文件名.我已经通过以下方式做到了这一点.但效率低下.
$fragment = $outFile ;
$count = index($fragment, "\\");
while($count > -1) {
$fragment = substr ($fragment, index($fragment, '\\')+1);
$count = index($fragment, '\\');
}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我一种方法,以有效的方式做到这一点.
Sin*_*nür 15
#!/usr/bin/env perl
use strict; use warnings;
use File::Basename;
my $outFile = "C:\\AOTITS\\BackOffice\\CSVFiles\\test.txt";
my ($name) = fileparse $outFile;
print $name, "\n";
Run Code Online (Sandbox Code Playgroud)
注意:您也可以使用正则表达式执行此操作,但在处理文件名时,请使用专门用于处理文件名的函数.为了完整起见,下面是使用正则表达式捕获最后一部分的示例:
my ($name) = $outFile =~ m{\\(\w+\.\w{3})\z};
Run Code Online (Sandbox Code Playgroud)
Eug*_*ash 11
关于标题中的问题,您可以使用以下rindex功能:
- rindex STR,SUBSTR,POSITION
rindex STR,SUBSTR
作品就像
index除了它返回的位置最后 SUBSTR的STR发生.如果指定了POSITION,则返回从该位置开始或之前开始的最后一次出现.
也就是说,解析文件路径更好File::Basename.