当我尝试使用嵌套的给定/ when语句时,为什么会出现“test3之后的错误名称”错误?

时间:2016-01-14 00:51:44

标签: perl switch-statement

使用Perl v5.10我试图嵌套given语句 - 即在满足其中一个初始given个案时调用when语句。例如:

my $value = "test3";
my $subvalue = "subtest2";
my $content .= "\nvalue:";

given($value) {
    when ('test1') { $content .= "test1" }
    when ('test2 ) { $content .= "test2" }
    when ('test3') {
        given($subvalue) {
            when ('subtest1') { $content .= "subtest1" }
            when ('subtest2') { $content .= "subtest2" }
            when ('subtest3') { $content .= "subtest3" }
            when ('subtest4') { $content .= "subtest4" }
        }
    }
}

我收到以下错误:

  

在test3'之后的错误名称....

是否可以在Perl v5.10中嵌套given语句?

3 个答案:

答案 0 :(得分:4)

从错误中,我怀疑您运行的代码不是您向我们展示的代码,并且有一个缺少的结尾 - '。 Perl在test3之前看到'作为结束引用,test3'作为限定标识符的开头('是旧的perl4方式说::)但没有其余的标识符。

$ echo 'Bad name after '|splain
Bad name after  (#1)
    (F) You started to name a symbol by using a package prefix, and then
    didn't finish the symbol.  In particular, you can't interpolate outside
    of quotes, so

        $var = 'myvar';
        $sym = mypack::$var;

    is not the same as

        $var = 'myvar';
        $sym = "mypack::$var";

splain / use diagnostics / perldoc perldiag可以成为你解读奇怪错误的朋友。

答案 1 :(得分:0)

我无法重现。我尝试了很多版本,包括5.10.1。

$ cat a.pl
use feature qw( switch );
no if $] >= 5.018, warnings => qw( experimental::smartmatch );

my $value = "test3";
my $subvalue = "subtest2";
my $content .= "\nvalue:";

given($value) {
    when ('test1') { $content .= "test1" }
    when ('test2') { $content .= "test2" }
    when ('test3') {
        given($subvalue) {
            when ('subtest1') { $content .= "subtest1" }
            when ('subtest2') { $content .= "subtest2" }
            when ('subtest3') { $content .= "subtest3" }
            when ('subtest4') { $content .= "subtest4" }
        }
    }
}

$ perl -c a.pl
a.pl syntax OK

您提供的错误与合格的软件包名称有关,但您提供的代码不包含任何:。我不相信您发布的代码会产生您声称的错误。

答案 2 :(得分:0)

您必须始终 use strictuse warnings位于每个Perl程序的顶部

您的代码适用于我。这是在Windows上的Perl v5.10.1上运行

use strict;
use warnings 'all';

use feature qw/ switch say /;
no warnings 'experimental';

my $value    = "test3";
my $subvalue = "subtest2";
my $content  = "\nvalue:";

given ($value) {
    when ('test1') { $content .= "test1" }
    when ('test2') { $content .= "test2" }
    when ('test3') {
        given ($subvalue) {
            when ('subtest1') { $content .= "subtest1" }
            when ('subtest2') { $content .= "subtest2" }
            when ('subtest3') { $content .= "subtest3" }
            when ('subtest4') { $content .= "subtest4" }
        }
    }
}

say $content;

输出

value:subtest2
相关问题