nath
nath

Reputation: 2848

how to find last index of string in perl

I am new to perl scripting. Can some one tell me how to find the last indexof substring in a string which is repeat several times in the string.

Actully I want to extract the file name from a give path

 $outFile = "C:\\AOTITS\\BackOffice\\CSVFiles\\test.txt";

If I can find the last string of the '\' I cand extract the file name using substr function. I already did that in the following way. But it is inefficient.

$fragment =  $outFile ;
$count = index($fragment, "\\");
while($count > -1) {
    $fragment =  substr ($fragment, index($fragment, '\\')+1);
    $count = index($fragment, '\\');
 }

Can some one tell me a way to do that in a efficient way.

Upvotes: 8

Views: 11060

Answers (3)

Eugene Yarmash
Eugene Yarmash

Reputation: 149973

Concerning the question in the title, you could use the rindex function:

  • rindex STR,SUBSTR,POSITION
  • rindex STR,SUBSTR

    Works just like index except that it returns the position of the last occurrence of SUBSTR in STR. If POSITION is specified, returns the last occurrence beginning at or before that position.

That said, it's better to parse file paths with File::Basename.

Upvotes: 14

tchrist
tchrist

Reputation: 80423

Can someone tell me how to find the last index of s substring in a string which is repeated several times in the string?

Yes.

my $whole = "Can someone tell me how to find the last index of s substring in a string which is repeated several times in the string?";
my $piece = "string";

my $place;
if ($whole =~ m { .* \Q$piece\E }gsx) {
    $place = pos($whole) - length($piece);
    print "Last found it at position $place\n";
} else {
    print "Couldn't find it\n";
}

But take Sinan’s answer, since he answered what you wanted to know, not what you asked. ☺

Upvotes: 4

Sinan Ünür
Sinan Ünür

Reputation: 118148

Use File::Basename:

#!/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";

NB: You can do this with regular expressions too, but when dealing with file names, use functions specifically designed to deal with file names. For completeness, here is an example of using a regular expression to capture the last part:

my ($name) = $outFile =~ m{\\(\w+\.\w{3})\z};

Upvotes: 15

Related Questions