【问题标题】:Why isn't my `my` variable accessible inside a sub?为什么我的 `my` 变量不能在 sub 中访问?
【发布时间】:2012-12-14 19:08:01
【问题描述】:

我正在编写一个 Mason 1.x 组件页面,但它的行为不像我预期的那样。 perlsub 手册页指出my 变量应该可以在sub 中访问。但是下面的代码:

my @myOrderBy = @orderBy;
sub sortAll
{
  my $ret = 0;
  foreach my $sortStr (@myOrderBy)
  {
  }
}

给我错误:

编译时出错 /opt/rt4/local/plugins/RTx-Foo/html/cf/helpers/ticketQuery.ajx: 变量“@myOrderBy”在以下位置不可用 /opt/rt4/local/plugins/RTx-Foo/html/cf/helpers/ticketQuery.ajx 第 206 行。

(第 206 行是foreach 行)

相同的代码在非 Mason 上下文中也能正常工作。

【问题讨论】:

    标签: perl scope mason


    【解决方案1】:

    my 变量仅在声明它们的代码块中可见。sub 是不同的代码块,因此 @myOrderBy 在其中不可用。见http://www.perlmonks.org/index.pl?node_id=66677

    【讨论】:

    • 不,这不是真的。正如我上面所说,代码在非 Mason 上下文中工作。另外,man perlsubThis doesn't mean that a "my" variable declared in a statically enclosing lexical scope would be invisible. Only dynamic scopes are cut off. For example, the "bumpx()" function below has access to the lexical $x variable because both the "my" and the "sub" occurred at the same scope, presumably file scope. my $x = 10; sub bumpx { $x++ }
    【解决方案2】:

    Mason 显然将您的代码包装在一个 sub 中(就像 mod_perl 一样)。这意味着你最终会得到类似的东西

    $ perl -we'sub { my $x; sub sortAll { $x } }'
    Variable "$x" is not available at -e line 1.
    

    解释很复杂,但归结为:Perl 不支持嵌套的命名子。尝试这样做会导致奇怪的错误。

    我可以建议你在这种情况下使用local our $x; 而不是my $x; 吗?

    【讨论】:

    • *sortAll = sub { 而不是sub sortAll {
    【解决方案3】:

    你不应该在 Mason 组件中使用命名的 subs,命名空间是共享的。改用这个:

    我的 $sortall = sub { ... };

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      相关资源
      最近更新 更多