2012-01-30 18 views

答えて

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

メソッド呼び出しの構文は$object->methodまたは$object->$methodです。ただし、与えた構文は$sub_ref->(@param)に使用できます。

9

Perlでは、記号->は2つの意味を持ちます。ベアワード$obj->nameまたはスカラー$obj->$nameが続く場合、->はメソッド呼び出しを意味します。

代わり->が開口ブレースが続いている場合、それは以下の表によれば、間接参照である:->値を逆参照されると

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

、perlは価値があるかどうかをチェックしますブレースによって示された型のいずれか、またはオーバーロードを介してその型に強制することができます。あなたの例の->(は、perlが$object_refをコードリファレンスに変換しようとしていることを意味し、おそらく失敗してエラーを投げます。

->は、メソッド呼び出しであれば、perlのようなものが行われます。ただ、物事をより明確にするために

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"} 

を:

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) 
関連する問題