Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Journal of IlyaM (2933)

Wednesday May 08, 2002
12:51 PM

Is it a number or a string?

[ #4768 ]
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.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.
  •   DB<8> p is_numeric(1.34)
      DB<9> p is_numeric('1.34')

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

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

      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


      Ilya Martynov ( [])