Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl regex not breaking out of until loop as expected

Tags:

regex

perl

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.

like image 208
Copas Avatar asked May 23 '09 19:05

Copas


2 Answers

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.

like image 51
Artem Russakovskii Avatar answered Nov 10 '22 03:11

Artem Russakovskii


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.

like image 30
Alan Haggai Alavi Avatar answered Nov 10 '22 02:11

Alan Haggai Alavi