-> 和有什么区别?和 :: 在 Perl 中 [英] What is the difference between -> and :: in Perl

查看:75
本文介绍了-> 和有什么区别?和 :: 在 Perl 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Perl 中 ::-> 之间的确切区别是什么?

What is the exact difference between :: and -> in Perl?

-> 有时会在 :: 不起作用的地方工作.

-> sometimes works where :: does not.

推荐答案

:: 有两个用途.

  1. 它是包名中的命名空间分隔符

  1. It's the namespace separator in package names

use Foo::Bar;    # Load Foo/Bar.pm
$Foo::Bar::var   # $var in namespace Foo::Bar

  • 附加到一个裸字后,它会创建一个字符串文字[1].

    以下与 'hello' 相同,只是它在包 hello 不存在时发出警告:

    The following is the same as 'hello' except it warns if the package hello doesn't exist:

    hello::
    

  • -> 有两个用途.

    1. 它用于取消引用.

    1. It's used to dereference.

    $array_ref->[$i]
    $hash_ref->{$k}
    $code_ref->(@args)
    

  • 在方法调用中使用它来表示调用者.

  • It's used in method calls to denote the invocant.

    CGI->new()        # Static method call
    $cgi->param()     # Object method call
    

  • <小时>

    您可能会问有什么区别


    You're probably asking what's the difference between

    Foo::Bar::mysub()
    

    Foo::Bar->mysub()
    

    前者是函数调用.后者是方法调用.方法调用类似于函数调用,但有两点不同:

    The former is a function call. The latter is a method call. A method call is like a function call with two differences:

    1. 方法调用使用继承.

    1. Method calls use inheritance.

    方法调用将调用者(-> 的剩余部分)作为第一个参数传递给 sub.

    Method calls pass the invocant (what's left of the ->) to the sub as its first argument.

    {
       package Foo::Baz;
       sub new {
          my ($class, $arg) = @_;
          my $self = bless({}, $class);
          $self->{arg} = $arg;
          return $self;
       }
    
       sub mysub1 {
          my ($self) = @_;
          print($self->{arg}, "\n");
       }
    }
    
    {
       package Foo::Bar;
       our @ISA = 'Foo::Baz'; 
       sub mysub2 {
          my ($self) = @_;
          print(uc($self->{arg}), "\n");
       }
    }
    
    my $o = Foo::Bar->new('hi');  # Same as: my $o = Foo::Baz::new('Foo::Bar', 'hi');
    $o->mysub1();                 # Same as: Foo::Baz::mysub1($o);
    $o->mysub2();                 # Same as: Foo::Bar::mysub2($o);
    

    <小时>

    注意事项


    Notes

    1. Foo->method 欺骗性地调用名为 Foo 的子(如果它存在)(使用它作为调用者返回的值).Foo::->method,意思是'Foo'->method,没有.
    1. Foo->method deceptively calls the sub named Foo if it exists (using its the value it returns as the invocant). Foo::->method, meaning 'Foo'->method, doesn't.

    这篇关于-> 和有什么区别?和 :: 在 Perl 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆