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!

Difficulty checking validity

Status
Not open for further replies.

aaronjonmartin

Technical User
Jul 9, 2002
475
GB
I have a variable in my script which should contain a number between one and 100, however I wish for my code to check this. Iam very new to perl so please excuse the easyness of this query. If the value in the variable is more than one hundred i wish my scipt to report an error. Thanx for any help
 
my $var = 101;

if( $var > 100 ){
print "var=$var, value too high, exiting\n";
exit 2;
} Mike

"Experience is the comb that Nature gives us, after we are bald."

Is that a haiku?
I never could get the hang
of writing those things.
 
Sorry my original post wasnt too clear, I need to first check if the variable is a number, if not then exit, then I need to check that it is a number between 1 and 100, if not then exit. Any more help on this would be appreciated.
 
This little beauty should do the trick:

print valcheck(101); # prints 2
print valcheck("text"); # prints 1
print valcheck(5); # prints 0

sub valcheck {
my $var = shift;
return 1 unless($var =~ /^\d+$/); # do we have a number?
return 2 if($var < 1 || $var > 100 ); # number in range?
return 0 # valid number
} Barbie
Leader of Birmingham Perl Mongers
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top