Perl:找到字符“\”的最后一次出现
Perl: find the last occurrence of the char "\"
我想从这样的文件字符串中删除路径:
Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml
我正在尝试查找最后一次出现的“\”的索引,以便我可以使用到那里的子字符串。
但我无法在搜索中使用字符“\”。我改用“\”,但它不起作用...
我正在尝试的代码:
$file = "Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml";
$tmp = rindex($file, "\");
print $tmp;
我得到的输出:
-1
我能做什么?
主要问题是您使用了无效的转义符:
use warnings;
print "Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml";
Unrecognized escape \T passed through at ... line 2.
Unrecognized escape \S passed through at ... line 2.
RootToOrganizationService_b37189b3-8505-4395_Out_BackOffice.xml
所以您的 $file
变量不包含您认为的内容。
你的 rindex
调用本身没问题,但你可以简单地这样做(假设你在 Windows 系统上):
use strict;
use warnings;
use File::Basename;
my $path = "Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml";
my $dir = dirname($path);
print "dir = $dir\n";
或者(这应该适用于任何系统):
use strict;
use warnings;
use File::Spec::Win32;
my $path = "Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml";
my $dir = (File::Spec::Win32->splitpath($path))[1];
print "dir = $dir\n";
请注意,如果这实际上是一个真正的 windows 路径,上面的代码将去除驱动器号(它是 splitpath
返回的列表的第一个元素)。
双引号内插转义\T和\S,所以你应该使用单引号'或q//来测试。无论如何,从文件中读取(例如,使用 <>)将为您工作,而无需更改与重新索引相关的代码,即这工作正常:
warn rindex ($_, "\") while (<>);
我想从这样的文件字符串中删除路径:
Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml
我正在尝试查找最后一次出现的“\”的索引,以便我可以使用到那里的子字符串。
但我无法在搜索中使用字符“\”。我改用“\”,但它不起作用...
我正在尝试的代码:
$file = "Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml";
$tmp = rindex($file, "\");
print $tmp;
我得到的输出:
-1
我能做什么?
主要问题是您使用了无效的转义符:
use warnings;
print "Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml";
Unrecognized escape \T passed through at ... line 2.
Unrecognized escape \S passed through at ... line 2.
RootToOrganizationService_b37189b3-8505-4395_Out_BackOffice.xml
所以您的 $file
变量不包含您认为的内容。
你的 rindex
调用本身没问题,但你可以简单地这样做(假设你在 Windows 系统上):
use strict;
use warnings;
use File::Basename;
my $path = "Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml";
my $dir = dirname($path);
print "dir = $dir\n";
或者(这应该适用于任何系统):
use strict;
use warnings;
use File::Spec::Win32;
my $path = "Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml";
my $dir = (File::Spec::Win32->splitpath($path))[1];
print "dir = $dir\n";
请注意,如果这实际上是一个真正的 windows 路径,上面的代码将去除驱动器号(它是 splitpath
返回的列表的第一个元素)。
双引号内插转义\T和\S,所以你应该使用单引号'或q//来测试。无论如何,从文件中读取(例如,使用 <>)将为您工作,而无需更改与重新索引相关的代码,即这工作正常:
warn rindex ($_, "\") while (<>);