0

I want to strip the path from a file string like this:

Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml

I am trying to find the index of the last occurrence of "\" so I can use substring up to there.

but I can't use the char "\" in the search. I am using "\" instead, but its not working...

my code i am trying :

$file = "Root\ToOrganization\Service_b37189b3-8505-4395_Out_BackOffice.xml";
$tmp = rindex($file, "\\");
print $tmp;

the OUTPUT I'm getting:

-1

What can I do?

Kenster
  • 23,465
  • 21
  • 80
  • 106
David Gidony
  • 1,243
  • 3
  • 16
  • 31

2 Answers2

5

The main problem is your use of invalid escapes:

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

So your $file variable doesn't contain what you think it does.

Your rindex call itself is fine, but you can simply do this (assuming you are on a Windows system):

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";

Or (this should work on any system):

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";

Note that if this is actually a real windows path, the code above will strip the drive letter (it's the first element of the list returned by splitpath).

melpomene
  • 84,125
  • 8
  • 85
  • 148
0

double-quotes interpolate escapes \T and \S, so you should use single quotes ' or q// to test. Anyway, reading from file (for example, with <>) will work for you without any changes in reindex-related code, i.e. this works fine:

warn rindex ($_, "\\") while (<>);
kabanoid
  • 106
  • 3