यदि $name='name'
$object_ref->$name
क्यों काम करता है लेकिन $object_ref->('name')
नहीं है?मैं पर्ल में एक शाब्दिक स्ट्रिंग में परिभाषित फ़ंक्शन नाम कैसे कॉल कर सकता हूं?
उत्तर
$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.
तो ->
एक विधि कॉल है, तो पर्ल की तरह कुछ करता है
के लिए सिंटेक्स विधि कॉल $object->method
या $object->$method
है। आपके द्वारा दिए गए वाक्यविन्यास का उपयोग $sub_ref->(@param)
के लिए किया जा सकता है।
पर्ल में, प्रतीक ->
दो अर्थ है। यदि कोई शब्द $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 $object_ref
को कोड संदर्भ में कनवर्ट करने का प्रयास करेगा, और संभवतः एक त्रुटि फेंकने में विफल हो जाएगा।
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)