Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find last index of string in perl

Tags:

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.

like image 308
nath Avatar asked Nov 18 '10 15:11

nath


People also ask

How do you find the index at the end of a string?

The lastIndexOf() method returns the index (position) of the last occurrence of a specified value in a string. The lastIndexOf() method searches the string from the end to the beginning. The lastIndexOf() method returns the index from the beginning (position 0).

How do you get last element of a string in the Perl?

Perl provides a shorter syntax for accessing the last element of an array: negative indexing. Negative indices track the array from the end, so -1 refers to the last element, -2 the second to last element and so on.

How do I index a string in Perl?

To search for a substring inside a string, you use index() and rindex() functions. The index() function searches for a substring inside a string from a specified position and returns the position of the first occurrence of the substring in the searched string.

How do I find the position of a character in a string in Perl?

Perl | index() Function This function returns the position of the first occurrence of given substring (or pattern) in a string (or text). We can specify start position.


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

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};
like image 91
Sinan Ünür Avatar answered Oct 06 '22 18:10

Sinan Ünür