How to run an anonymous function in Perl?

前端 未结 7 2023
长发绾君心
长发绾君心 2021-01-31 08:57
(sub {
print 1;
})();



sub {
print 1;
}();

I tried various ways, all are wrong...

7条回答
  •  难免孤独
    2021-01-31 09:44

    There is not much need in Perl to call an anonymous subroutine where it is defined. In general you can achieve any type of scoping you need with bare blocks. The one use case that comes to mind is to create an aliased array:

    my $alias = sub {\@_}->(my ($x, $y, $z));
    
    $x = $z = 0;
    $y = 1;
    
    print "@$alias"; # '0 1 0'
    

    Otherwise, you would usually store an anonymous subroutine in a variable or data structure. The following calling styles work with both a variable and a sub {...} declaration:

    dereference arrow:  sub {...}->(args)  or  $code->(args)
    
    dereference sigil:  &{sub {...}}(args) or &$code(args)
    

    if you have the coderef in a scalar, you can also use it as a method on regular and blessed values.

    my $method = sub {...};
    
    $obj->$method           # same as $method->($obj)
    $obj->$method(...)      # $method->($obj, ...)
    
    [1, 2, 3]->$method      # $method->([1, 2, 3])
    [1, 2, 3]->$method(...) # $method->([1, 2, 3], ...)
    

提交回复
热议问题