regex - Perl:使用 ?: 运算符时出现意外匹配变量

标签 regex perl cgi taint-checking

尝试清除 Perl 中的一些变量,以下代码效果很好:

if ($year =~ /^(\d{4})$/) {
        $year = $1;
} else {
        &invalid("year");
}

在上面的例子中,如果有效,$1 包含 $year。但是,当使用 ?: 运算符时,$1 在有效时包含“1”:
($year =~ /^(\d{4})$/) ? $year = $1 : &invalid("year");

任何人都知道我可能有错吗?我很困惑为什么会这样。它只发生在这台机器上。或者更确切地说,我已经成功地使用了 ?用于返回正确匹配变量多年的运算符。我还没有在任何其他机器上尝试过这段代码。
This is Perl, v5.8.8 built for x86_64-linux-thread-multi

最佳答案

请注意这里的优先级。

将按预期工作的 http://codepad.org/vEPnhWfH 与不工作的 http://codepad.org/nXVU5CA7 进行对比。当然,我稍微调整了代码以避免调用 invalid ,但我怀疑这可能是问题的根源。

在这两种情况下,虽然 $1 包含“2011”,所以也许您应该按照 mu 的第一条评论中的要求显示其他代码。

更新

我更改了键盘示例以使用对 &invalid 的调用,并且错误没有出现。

sub invalid {
    print("INVALID\n");
}

sub check_with_if {
    print("Trying with if-statement\n");
    my $year = shift;
    if ($year =~ /^(\d{4})$/) {
        $year = $1;
    } else {
        &invalid($year);
    }
    print("\$1 is $1 and \$year is $year"."\n");
}

sub check_with_conditional {
    print("Trying with conditional expression\n");
    my $year = shift;
    ($year =~ /^(\d{4})$/) ? $year = $1 : &invalid($year);
    print("\$1 is $1 and \$year is $year"."\n");
}

check_with_if("2011");
check_with_conditional("2011");

输出是
Trying with if-statement 
$1 is 2011 and $year is 2011
Trying with conditional expression
$1 is 2011 and $year is 2011

http://codepad.org/z22GMEcn

编辑 2 也适用于 Mac 上的 5.12.3。

我同意 Jonathan 的观点,您可能在 5.8.8 中发现了一个自那时以来已修复的错误。如果您非常好奇,可以按照自己的方式进行 Perl 更改,例如:
  • http://search.cpan.org/~jesse/perl-5.14.1/pod/perl5100delta.pod (5.8.8 -> 5.10.0)
  • http://search.cpan.org/~jesse/perl-5.11.1/pod/perl5110delta.pod (5.10.0 -> 5.11.0)
  • http://search.cpan.org/~jesse/perl-5.12.0/pod/perl5120delta.pod (5.10.0 -> 5.12.0)
  • 关于regex - Perl:使用 ?: 运算符时出现意外匹配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7314676/

    相关文章:

    php - 正则表达式/SQL - 查找 "WHERE"但不在括号之间

    javascript - 正则表达式查找所有至少包含一个星号的单词

    D 中的 CGI 编程

    php - 在 mailto : replace subject and body adding %20 instead space in all file php using notepad++

    xml - 如何使 Perl XML::XPath 允许没有命名空间前缀的查询?

    perl - perl 模块可以 "use"其他 perl 模块吗?

    perl:如何区分文件是否不存在或我对路径没有权限

    python - 为什么 python-cgi 在 unicode 上失败?

    google-app-engine - Python 2.7 App 在 App Engine 上作为 CGI 而不是 WSGI 执行

    regex - 使用 [ :word:] gives: Invalid character class name 删除单词