Is it possible to create associative array that returns function? Something similar to this
%a = ('first' => sub first { $x = @_; sprintf("(first %s)", $x); });
Thank you
It is possible, but you probably want my ($x) = @_; instead of $x = @_; and drop function name as you're dealing with anonymous function.
You can then call function as $a{first}->([arg])
my %a = ('first' => sub { my ($x) = @_; sprintf("(first %s)", $x); });
So close... The one detail you missed is that you're defining an anonymous sub there, so you shouldn't give it a name:
$ perl -E '%a = (first => sub { $x = @_; sprintf("(first %s)", $x); }); say $a{first}->(3);'
(first 1)
(Note that, with $x = @_, you're setting $x to the number of items in @_, not the first item in the array, which is why the output is "first 1" instead of "first 3".)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With