Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: How to check if a scalar value is numeric or string?

by biohisham (Priest)
on Aug 27, 2009 at 15:21 UTC ( [id://791677]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://791677]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-24 05:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found