Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^2: substr outside of string

by hgolden (Pilgrim)
on Sep 09, 2006 at 13:49 UTC ( [id://572147]=note: print w/replies, xml ) Need Help??


in reply to Re: substr outside of string
in thread substr outside of string

Rob is right that it's just throwing a warning and not an error. The question is what you want to happen if the index is greater than the length of the string. If exiting is what you'd like, then you have a fine solution. If you're happy to print a blank, then you don't have to worry too much about the warning at all. If you'd like a different behavior if the index is greater than the string length, then set up a conditional:
if (length($str) < $index) { $s=substr($str,$index,1); } else { whatever else }
I hope this helps, and reply if you need any more help. Hays

Edit: Removed the poorly placed  my

Replies are listed 'Best First'.
Re^3: substr outside of string
by ikegami (Patriarch) on Sep 09, 2006 at 18:40 UTC
    Your my is rather useless inside the "then" clause. May I recommend the following variation:
    my $s = (length($str) < $index ? substr($str, $index, 1) : '' # or undef, or die, or ... );
      Good point. I'd copied that line out of the original code and hadn't thought about it. Thanks for the catch.

      Hays

Re^3: substr outside of string
by Anonymous Monk on May 03, 2012 at 05:23 UTC
    Pardon me if I am wrong, but shouldn't it be
    if (length($str) > $index) { $s = substr($str, $index, 1); } else { whatever else }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2025-05-24 12:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.