in reply to Re: Why does sv_2nv on non-number look like an NV
in thread Why does sv_2nv on non-number look like an NV

How can you turn "aa" into a double?

  • Comment on Re^2: Why does sv_2nv on non-number look like an NV

Replies are listed 'Best First'.
Re^3: Why does sv_2nv on non-number look like an NV
by ikegami (Patriarch) on Nov 26, 2009 at 15:41 UTC
    With difficulty. You get zero
    >perl -e"print 0+'aa'" 0

      It appears to me you've taken my comment followup as a literal question rather than what I meant which is why would sv_2nv convert "aa" to a 0 double and how may I avoid this but still have it work for real numbers.

      I would like the code above to convert the sv to a double when that is reasonable and not otherwise and I'd like to know when it cannot do it.

        Maybe use looks_like_number(sv) prior to calling sv_2nv ...

        #!/usr/bin/perl use Inline C => <<'END_C'; void num_test(SV* sv) { I32 is_num = looks_like_number(sv); printf("'%s' looks like a number: %s (SvNV(): %g)\n", SvPV_nolen(sv), is_num ? "yes":"no", SvNV(sv) ); } END_C num_test('aa'); num_test('123'); num_test('123aa'); num_test('aa123'); num_test('1.23'); __END__ 'aa' looks like a number: no (SvNV(): 0) '123' looks like a number: yes (SvNV(): 123) '123aa' looks like a number: no (SvNV(): 123) 'aa123' looks like a number: no (SvNV(): 0) '1.23' looks like a number: yes (SvNV(): 1.23)

        Update: added SvNV() results for comparison.

        why would sv_2nv convert "aa" to a [...] double

        Because you asked it to.

        how may I avoid this but still have it work for real numbers.

        If you need an NV, "aa" would be an error. There are ways of checking that (looks_like_number), but you say you don't want that.

        If you need an SV that contains a number if possible, you already have that. You don't need to do anything. Useless numifying is useless.

        If it's not useless, it's because you have code that treats PV 1.2 different than NV 1.2, and that's a bug. Perl has an example of that (bitwise ops), and it has caused many headaches.