Hi Tom,

What you're experiencing is not a bug. It's the fact that if 0 ends up
in your $idx variable, then that 0 will evaluate as False in an if
statement (or in a && operand).

But jumping ahead to what you probably *meant* to write:

if defined($idx) && $idx >= 0 {
  $str = $str.substr(0, $idx);
}

That should work for you.

$idx.defined also works.

Perl allows you to be as loose or as specific as you want in these
cases. If you only say `$idx`, then all "interesting values" are true,
like nonzero numbers, nonnegative strings, etc. All "empty" values are
false: zero, empty string, empty list, undefined values, etc. If you
want to allow zero but disallow something undefined, you have to be
more specific, as above.

Regards,
// Carl

On Fri, Jul 3, 2015 at 2:07 PM, Tom Browder <tom.brow...@gmail.com> wrote:
> I originally had problems with the S32 description of string function
> index. S32 says that if the substring is not found then a bare Int is
> returned which evaluates to false, otherwise an Int with the position
> of the first substring match is returned. It goes on to say that one
> should not evaluate the result as a number.  So my question was, how
> does one practically use that information for a substring that starts
> at position zero which evaluates as false?
>
> Based on the S32 description, I first tried this to remove a comment
> from a data line:
>
>   my $str = '# a comment';
>   my $idx = $str.index('#');
>   if $index && $index >= 0 {
>     $str = $str.substr(0, $idx);
>   }
>
> It didn't work for a comment at position zero but it found one at any
> other position or no comment at all.  Then I tried this:
>
>   if $idx {
>     $str = $str.substr(0, $idx);
>   }
>
> Same result as the previous method: it would not report a substring at
> position zero.
>
> So what am I doing wrong for finding position zero substrings?
>
> Best,
>
> Tom
>
> P.S.  The S32 description I believe should note that the default value
> of the index starting position is 0.

Reply via email to