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.
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).
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.
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.
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.
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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With