When I print the result of the regex I am attempting to use to control the until loop it gives me the 1 or null I am expecting. Why is it that the code below won't work but if I uncomment the fifth line it works fine?
print("Please enter 1, 2, 3 or 4 : ");
my $channelSelection = "";
until ($channelSelection =~ /^[1-4]$/) {
chomp(my $channelSelection = <STDIN>);
#last if ($channelSelection =~ /^[1-4]$/);
print ("Invalid choice ($channelSelection) please try again: ")
if ($channelSelection !~ /[1-4]/);
}
I'm sure this has been solved elsewhere but was unable to find it with search. Pointing me in the right direction would be great.
I would normally do something like.
print("Please enter 1, 2, 3 or 4 : ");
my $channelSelection = "";
while (1) {
chomp(my $channelSelection = <STDIN>);
last if ($channelSelection =~ /^[1-4]$/);
print ("Invalid choice ($channelSelection) please try again: ") if ($channelSelection !~ /[1-4]/);
}
But I'm trying to get away from the infinite loops.
The problem here is you're re-declaring the $channelSelection within the loop but the outside of the loop keeps the old value. Remove the "my" from the inner loop.
You have redeclared $channelSelection
locally within the until loop. That way, its value will be lost every time the loop executes. So the regular expression will not match as the then value of $channelSelection
will again be equal to ""
.
Removal of my
from within the loop will solve the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With