General discussion

Locked

Find substrings with index and rindex

By Mark W. Kaelin Editor ·
The Nov. 12 Perl TechMail, "Find substrings with index and rindex," described several possible uses for Perl?s two index functions, index and rindex. Have you used these functions to find the offset of a substring in your Perl applications?

This conversation is currently closed to new comments.

1 total post (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

Subscriber comment

by Mark W. Kaelin Editor In reply to Find substrings with inde ...

A subscriber e-mailed this comment/question and our Perl tip writer offered his response:

I always enjoy your Perl tips. I had one comment on your example.

You did not choose a good example for rindex since there is a much easier way to do your example:

$file = substr($path, rindex($path, '/')+1);

Here is an easier way to do it:

$file = $path;
$file =~ s:.*/::; # works since * is greedy

PS Do you know any way to do my two example in one line?

Answer *****************
You are correct that there are easier ways to return the last element of a
path. However, this code was meant as a simple example of the purpose of
the function, not necessarily the best way to do a specific task. Remember
the Perl motto: "There is more than one way to do it!"

Also keep in mind that the pattern matching operators are not as time
efficient as the index functions.

In answer to your second question, yes you can combine the two statements
into a single line as follows:
($file = $path) =~ s:.*/::;

The parens around the assignment are necessary because of binding
precedence. Without them, $file would be the boolean result of the
substitution (a 0 or 1) and the actual substitution would have been
performed onthe contents of $path. By using the parens you are telling
Perl to do the assignment first, then use the result of the assignment (the
left-hand variable) to do the next operation (substitution).

You could also achieve the same result like this:

($file) = $path =~ m:([^/]*)$:;

This works because in list context, the pattern matching operators return
the list of matched sub-patterns ($1, $2, $3, etc.). The parens around
$file are necessary to force list context. Without the parens $file would
again be either 0 or 1 depending on the success or failure of the match.

Back to Web Development Forum
1 total post (Page 1 of 1)  

Related Forums