Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check for numeric value in Variable 2

Status
Not open for further replies.

skosterow

Technical User
Feb 23, 2002
135
US
Okay NOT asking for the code asking for direction.

I need to check and see if a variable has a numaric value or a char value.

IE -

$val1 = "2345b";

if ($val1 is all numaric) { do this....
} else { do this... }

in this instance the else would be executed because $val1 has a 'b' in it.....

thanks in advanced

- Scott

Wise men ask questions, only fools keep quite.
 
Do this

Code:
if ($val1 =~ m/\D/g) {
  print "All are not digits\n";
}
else {
  print "There are some digits\n";
}
 
Thanks varakal -

BTW do you know of something i can learn about what is going on in that code?

I appreshiate the answer however KUDOS!!!

- Scott

Wise men ask questions, only fools keep quite.
 
It is simple. You are searching through the variable $var1 for a character that is not a digit. '\D' looks for chars that are not digits, where are '\d' looks for chars that are digits. 'g' tells to look through all the chars, just not the first or last.
Take a look at

Hope this helps.
 
Thanks again Varakal!

Wise men ask questions, only fools keep quite.
 
varakal - that regexp isn't doing what you think it is - it's more like this:
Code:
if ($val1 =~ m/\D/g) {
  print "Not all are digits\n";
}
else {
  print "All are digits\n";
}

To get the behaviour you were expecting, you'd have to check that ALL the characters in the string weren't digits. Currently, your regexp checks for one non-digit only. It would become:
Code:
if ($val1 =~ m/^\D*$/) {
  print "All are not digits\n";
}
else {
  print "There are some digits\n";
}
 
Ohh ya.. my bad.. I always misinterpret search 'm' with replace 's'.
 
Okay here we are the battle of the regexp! ;-)

thanks ishnid!

Wise men ask questions, only fools keep quite.
 
skosterow, you might want to try perldoc -q scalar and take a look at "How do I determine whether a scalar is a number/whole/integer/float?"


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top