How to find the last row index in perl

I am new to perl scripts. Can someone tell me how to find the last index of a substring in a string that repeats several times in a string.

Actully I want to extract the file name from the transfer path

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

If I can find the last line '\', I want to extract the file name using the function substr. I already did it as follows. But it is inefficient.

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

Can someone tell me a way to do this in an efficient way.

+5
source share
3 answers

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

. , , . :

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

, rindex:

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

    , index, , SUBSTR STR. POSITION, , .

, File::Basename.

+10

- , s , ?

.

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 answer the Sinai, for he answered what you wanted to know, not what you asked.

+4
source

All Articles