in reply to How to check if a scalar value is numeric or string?

I tried to do it using regular expressions but I couldn't have a clear shot, there is another feature, use the complement operator, In order to determine if a variable is a number or a string, employ the principle that &ing a variable with its complement should give 0 as a result if that variable holds a number, whereas it is not the case when that variable is a string.

try extending on this principle, here is a snippet:

my $x=111; my $y="111"; print "\$x is a number\n" if !($x & ~$x); print "\$y is a string\n" if ($y & ~$y);

Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind.

Replies are listed 'Best First'.
Re^2: How to check if a scalar value is numeric or string?
by ikegami (Patriarch) on Aug 27, 2009 at 16:18 UTC

    By the way, $x & ~$x can also be written as $x ^ $x.

      As of perl 5.24 you can no longer use this trick because ^ does not like strings with code points over 0xFF. Right now it is deprecated, but will presumably be fatal later.

        Hi, this is day 2 of my perl journey and I'm doing some exercises in Learning Perl. Where can I read more on what ^ was, why it was deprecated, and on $x & ~$x?

Re^2: How to check if a scalar value is numeric or string?
by bgupta (Novice) on Aug 27, 2009 at 16:07 UTC
    Many thanks, you saved my day, this approach works perfectly for me.

      But watch out for side effects.

      my $x = 1; my $y = '1'; print "x is a ", (($x ^ $x)?"string":"number"), "\n"; print "y is a ", (($y ^ $y)?"string":"number"), "\n"; print "\$x = $x\n"; print "\$y = $y\n"; print "x is a ", (($x ^ $x)?"string":"number"), "\n"; print "y is a ", (($y ^ $y)?"string":"number"), "\n"; my $z = $x + $y; print "\$z = $z\n"; print "x is a ", (($x ^ $x)?"string":"number"), "\n"; print "y is a ", (($y ^ $y)?"string":"number"), "\n";

      gives

      x is a number y is a string $x = 1 $y = 1 x is a number y is a string $z = 2 x is a number y is a number

      It might be better to revise your program so that it doesn't depend on such a subtle distinction.