nath nath - 5 months ago 7
Perl Question

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.

Answer

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