2012-01-30 33 views

Trả lời

3
$obj->$name  # Method call with no args 
$obj->name  # Method call with no args 
$obj->$name()  # Method call with no args 
$obj->name()  # Method call with no args 

$sub->('name') # Sub call (via ref) with one arg. 
sub('name')  # Sub call with one arg. 
1

Cú pháp cho các cuộc gọi phương thức là $object->method hoặc $object->$method. Tuy nhiên, cú pháp bạn đã cung cấp có thể được sử dụng cho $sub_ref->(@param).

9

Trong Perl, ký hiệu -> có hai nghĩa. Nếu được theo sau bởi một chủ thể $obj->name hoặc vô hướng $obj->$name thì -> nghĩa là gọi phương thức.

Nếu thay vào đó là -> Tiếp theo là một cú đúp mở cửa, sau đó nó là một dereference, theo bảng sau:

$obj->(...) # dereference as code, which calls the subroutine 
$obj->[...] # dereference as array, which accesses an element 
$obj->{...} # dereference as hash, which accesses an element 

Khi -> được dereferencing một giá trị, perl sẽ kiểm tra xem nếu giá trị là hoặc là loại được chỉ định bởi cú đúp hoặc nếu nó có thể bị ép buộc vào loại đó thông qua quá tải. Vì vậy, ->( trong ví dụ của bạn có nghĩa là perl sẽ cố gắng chuyển đổi $object_ref thành tham chiếu mã và có thể sẽ không thành công, sẽ xảy ra lỗi.

Nếu -> là một phương pháp gọi, sau đó perl làm điều gì đó như:

if (reftype $name eq 'CODE') { # if $name is code, ignore $object_ref's type 
    $name->($object_ref)  # call the coderef in $name, with $object_ref 
}        # followed by any other arguments 

elsif (my $code = $object_ref->can($name)) { # otherwise, try to look up the 
    # coderef for the method named $name in $object_ref's namespace and then 
    $code->($object_ref) # call it with the object and any other arguments 
} 
else {die "no method $name on $object_ref"} 

Chỉ cần để làm cho mọi việc rõ ràng hơn:

sub foo {"foo(@_)"} 

my $foo = \&foo; 

say foo 'bar';  # 'foo(bar)' 
say $foo->('bar'); # 'foo(bar)' 
say 'bar'->$foo; # 'foo(bar)' 

sub Foo::bar {"Foo::bar(@_)"} 
my $obj = bless [] => 'Foo'; 

my $method = 'bar'; 

say $obj->bar(1);  # Foo::bar($obj, 1) 
say $obj->$method(1); # Foo::bar($obj, 1) 
Các vấn đề liên quan