in reply to substr outside of string

There's actually no error - all you're seeing is a couple of warnings because you have warnings enabled.

If you really want to exit if the substr is outside of the string, then I can't think of any option significantly different to the one you've suggested.

If you're more interested in just not seeing the warnings you could disable warnings altogether or change the code to:
use warnings; no warnings ('uninitialized', 'substr'); my $str="name"; my $index=12; my $s=substr($str,$index,1); print $s;

Cheers,
Rob

Replies are listed 'Best First'.
Re^2: substr outside of string
by hgolden (Pilgrim) on Sep 09, 2006 at 13:49 UTC
    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

      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

      Pardon me if I am wrong, but shouldn't it be
      if (length($str) > $index) { $s = substr($str, $index, 1); } else { whatever else }