How can I name a function name defined in a literal string in perl?

If it $name='name'works $object_ref->$name, but not $object_ref->('name')?

+5
source share
3 answers
$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.
+3
source

In Perl, a symbol ->has two meanings. If it is followed by a single word $obj->nameor scalar $obj->$name, it ->means a method call.

If an ->opening bracket follows instead , it will be dereferenced according to the following table:

$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 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 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)
+9

The syntax for method calls is $object->methodor $object->$method. However, the syntax you gave can be used for $sub_ref->(@param).

+1
source

All Articles