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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check to see if string is a number. 1

Status
Not open for further replies.
Joined
Jun 19, 2001
Messages
86
Location
US
I need to verify that what someone enters is a number and not a word. I thought that something like this:

if ($keyword == 0..1000000){
print "It's a number!";
} else {
print "It's not a number";
}

would work but it doesn't.
 
How about using a regular expression, like:

if ($keyword =~ /^\d+$/) {
print "\$keyword $keyword is a number\n";
}
else {
print "\$keyword $keyword is NOT a number\n";
}

Read your perldoc info on regular expressions - on *nix, do

perldoc perlre

HTH.
Hardy Merrill
Mission Critical Linux, Inc.
 
Thank you so much. It worked like a charm!
 
Here's another option that is sometimes useful. You can negate a class in the regex with the ^.

#!/usr/local/bin/perl
$keyword = '123s';
# if $keyword contains anything other than digits.
if ($keyword =~ /[^\d]/) { print "non-digit\n"; }
else { print "just digits\n"; }

TIMTOWTDI ;-)


keep the rudder amid ship and beware the odd typo
 
I didn't realize that metacharacters like \d would work inside a class. You can also negate the search itself, like this:
Code:
if ($keyword !~ /^\d+$/) { print "non-digit\n"; }
else { print "just digits\n"; }
The key is to use !~ instead of =~
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top