|
I need to write a basic program for class. if the user enters a string when asked for a number value, the proram should ask again, if a number is entered the program should continue with the next question. My problem is that the program loops regardless of what is entered. Here is the code, please show me what is wrong.
$a=0;
until ($a==1)
{
print "Enter the starting amount for your retirement account:";
chomp ($starting=<STDIN>);
if ($starting == " ")
{
print "Invalid Input\n";
}
else
{
$a==1;
}
}
|
|
|
Well formating seems to be a bit of a pain on this forum, which it would let you indent! Here are some minor changes to a style i like, you don't have to use the same style but its always nice to see how other people do things, take what you like, leave what you don't.
my $a=0; #added my to declare your variable, always good practice
until ($a==1) {
print "Enter the starting amount for your retirement account:";
chomp ($starting=<STDIN>);
if ($starting == " ") {
print "Invalid Input\n";
} else {
$a==1;
}
}
Now first off == means to check for the numeric equality. So your are going to loop UNTIL $a is equal to 1. You print out your prompt and get the data back in starting. You then ask if $starting is numericaly equal to a space, which is probably going to be zero unless you user enters 0 which is probably not going to happen. If they didn't enter 0 then you are useing == agian which actualy checks to see if $a is equal to 1, it doesn't set $a.
To fix it, change $starting == " " to a condition that will be true for a string instead of a number. $a =~ /\D/ is a regex that will be true if $a contains anything that is not a digit (\d is a digit \D is anything thats not a digit). Then change your == to = so that it will be an assignment instead of a condition.
Good luck!
|
|
|
|
|
|
|
|