Perl正则表达式没有像预期的那样突破到循环

Cop*_*pas 7 regex perl

当我打印我试图用来控制until循环的正则表达式的结果时,它给我1或者我期待的null.为什么下面的代码不起作用,但如果我取消注释第五行它可以正常工作?

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]/);
}
Run Code Online (Sandbox Code Playgroud)

我确信这已在其他地方得到解决,但无法通过搜索找到它.把我指向正确的方向会很棒.

我通常会做类似的事情.

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]/);
}
Run Code Online (Sandbox Code Playgroud)

但我正试图摆脱无限循环.

Art*_*kii 18

这里的问题是你在循环中重新声明$ channelSelection,但循环外部保留旧值.从内循环中删除"我的".


Ala*_*avi 11

您已$channelSelection在until循环中本地重新声明.这样,每次循环执行时它的值都会丢失.所以正则表达式将不匹配,因为then的值$channelSelection将再次等于"".

my从循环内移除将解决该问题.


Sin*_*nür 6

怎么不担心呢?

#!/usr/bin/perl

use strict;
use warnings;

use Term::Menu;

my @channels = qw( 1 2 3 4 );

my $prompt = Term::Menu->new(
    aftertext => 'Please select one of the channels listed above: ',
    beforetext => 'Channel selection:',
    nooptiontext =>
        "\nYou did not select a valid channel. Please try again.\n",
    toomanytries =>
        "\nYou did not specify a valid channel, going with the default.\n",
    tries => 3,
);

my $answer = $prompt->menu(
    map { $_ => [ "Channel $_" => $_ ] } @channels
);

$answer //= $channels[0];

print "$answer\n";

__END__
Run Code Online (Sandbox Code Playgroud)