【问题标题】:Why is `a::->func;` valid?为什么`a::->func;`有效?
【发布时间】:2011-11-10 08:30:18
【问题描述】:
package a;
sub func {
print 1;
}
package main;
a::->func;

IMO 有 a::func,a->func 就足够了。

a::->func; 我觉得很奇怪,为什么 Perl 支持这种看起来很奇怪的语法?

【问题讨论】:

  • 如果你觉得那个语法很奇怪...
  • Perl 不需要理由也不需要借口。 Perl 就是 Perl。
  • @pst - 我敢给你介绍一个陌生人 :)

标签: perl


【解决方案1】:

引用 chromatic 最近关于该主题的出色博客文章 Modern Perl blog:“避免裸词解析歧义。”

为了说明这种语法为何有用,以下是从您的示例演变而来的示例:

package a;
our $fh;
use IO::File;
sub s {
    return $fh = IO::File->new();
}

package a::s;
sub binmode {
    print "BINMODE\n";
}

package main;
a::s->binmode; # does that mean a::s()->binmode ?
               # calling sub "s()" from package a; 
               # and then executing sub "open" of the returned object?
               # In other words, equivalent to $obj = a::s(); $obj->binmode();
               # Meaning, set the binmode on a newly created IO::File object?

a::s->binmode; # OR, does that mean "a::s"->binmode() ?
               # calling sub "binmode()" from package a::s; 
               # Meaning, print "BINMODE"

a::s::->binmode; # Not ambiguous - we KNOW it's the latter option - print "BINMODE"

【讨论】:

    【解决方案2】:

    a:: 是产生字符串a 的字符串文字。都一样:

     a->func()    # Only if a doesn't exist as a function.
     "a"->func()
     'a'->func()
     a::->func()
     v97->func()
     chr(97)->func()
    

    >perl -E"say('a', a, a::, v97, chr(97))"
    aaaaa
    

    【讨论】:

    • +1。如果您告诉我如何忘记最后两个,则再 +1。
    • @DVK,chr是一个非常有用的功能。不过,这显然不是使用它的地方。 v97 是版本字符串,作为版本字符串用起来也不是特别好。
    猜你喜欢
    • 1970-01-01
    • 2010-12-16
    • 2017-12-13
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多