kulls has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
Can anyone suggest me how to get ride of this error/ capture this error when my search index is more than the length of the string ?.
#!c:\bin\perl use warnings; my $str="name"; my $index=12; my $s=substr($str,$index,1); print $s; __OUTPUT__ substr outside of string at - line 3. Use of uninitialized value in print at - line 4.

Can I add this line before the assignment ? Is there any other option ?
exit if(length($str)< $index);
Thanks
-kulls

Replies are listed 'Best First'.
Re: substr outside of string
by syphilis (Archbishop) on Sep 09, 2006 at 10:21 UTC
    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
      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 ... );
        Pardon me if I am wrong, but shouldn't it be
        if (length($str) > $index) { $s = substr($str, $index, 1); } else { whatever else }