Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associative array that returns function in perl

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

like image 753
user1706754 Avatar asked Aug 23 '26 11:08

user1706754


2 Answers

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); });
like image 143
mpapec Avatar answered Aug 25 '26 15:08

mpapec


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".)

like image 35
Dave Sherohman Avatar answered Aug 25 '26 15:08

Dave Sherohman