Is it a number or a string?

IlyaM on 2002-05-08T17:51:55

Coolest Perl trick I've learned recently:

sub is_numeric { ($_[0] & ~ $_[0]) eq "0"; }

I found this gem when I was reading this thread about DBI::PurePerl.


Explain this then!

sharkey on 2002-05-31T00:52:22

  DB<8> p is_numeric(1.34)
1
  DB<9> p is_numeric('1.34')

  DB<10>

Re:Explain this then!

IlyaM on 2002-05-31T07:15:17

It is based on the fact that operator '~' gives different result if it given string argument instead of numeric.

DB<4> p ~ 100
4294967195
DB<5> p ~ '100'
XXX

where XXX some chars from second half of ASCII table.

With numeric argument '~' acts as usual bitwise negation operator. With string argument it acts like

join '', map chr((~ord) & 255), split //, $arg