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 }