Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Problem with substr

by kennethk (Abbot)
on May 14, 2013 at 16:03 UTC ( #1033518=note: print w/ replies, xml ) Need Help??


in reply to Problem with substr

If rindex has no matches, it returns -1. If substr gets a negative OFFSET, it "starts that far back from the end of the string". The correct approach here would be to test the result of rindex, and only modify if the number is non-negative:

if ((my $index = rindex( $name, q{.replaced})) > -1 ) { $name = substr $name, 0, $index; }

Note as well that you have an off-by-one error on your replacement, which I have fixed by adding '.' to your string.

Update: AnomalousMonk caught that the rindex was in the LENGTH argument, not the OFFSET argument.

If LENGTH is negative, leaves that many characters off the end of the string.

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.


Comment on Re: Problem with substr
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1033518]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (12)
As of 2015-07-28 16:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (258 votes), past polls