I am trying to make a program that simulates a line at a grocery storye.
if a is entered, it allows for users to add names.
if c is entered, it simulates a person leaving the line.
if p is entered, it prints the list of names.
if q is entered, it quits.
my code just results in an infinite loop and I am not sure why. Every time I try and enter in values, it just reads invalid input and wont exit. I am not sure if the other stuff is working or not but that is not what I need help with.
$choice="";
$name;
@line=();
print "\n";
print "Choose an option:\n";
print "a: Add person to end of line\n";
print "c: Call the next person in line\n";
print "p: Print the list of people in line\n";
print "q: Quit\n";
print "\n";
while ($choice ne "q") {
print "Your choice:";
$choice = <>;
print "\n";
if($choice eq "a") {
print "Enter name:";
$name = <>;
push(@line,$name);
}
elsif ($choice eq "c") {
shift(@line);
}
elsif ($choice eq "p") {
for ($i=0;$i<=scalar(@line);$i++) {
print (@line[$i]);
}
}
elsif ($choice eq "q") {
exit;
}
else {
print "Invalid option";
}
}
As @stark has correctly pointed out, the main issue with your loop is that you’re not removing the newline after getting your input from STDIN. So, $choice will never match your options and you will never break out of the loop. Try changing:
to
Notice that you’ll need to
chomp $choicein order to remove the newline before you do your string comparison.Also, try writing your scripts with “use warnings” and “use strict”. This will pick up a lot of little errors you may not otherwise have noticed. For example, your script might look something like this: