Is it possible to define anonymous subroutines in a hash constructor?
I'm trying to do something like this:
My% array = {one = & gt; Sub (print "first $ _ [0]"}, two => sub (print "next $ _ [0]"}, three => sub (print "last $ _ [0]"}}; $ Array {$ foo} - & gt; ('talk');
But it does not work, it starts running and compiling the code, but values are empty in the array. If I do this:
my% array; $ array {'one'} = sub {print "first $ _ [0]"}; $ array {'two'} = sub $ {Array} {$ foo} -> / Code> Then it starts to work fine. Sass is an alternative solution, but this is just to annoy me and I wonder if someone knows that this is possible and, if so, what the syntax is.
It seems that you are being misquoted in a hash. Using {}
creates an anonymous hash reference, which You specify a scalar but you are specifying a named hash (% array
).
Must specify:
My $ array = {one => Sub (print "first $ _ [0]"}, two => sub (print "next $ _ [0]"}, three => sub (print "last $ _ [0]"}}; $ Array- & gt; {$ foo} - & gt; ('talk');
or not to use the non constructor syntax:
< Code> my% array = (a => sub {print "first $ _ [0]"}, two => sub (print) "next $ _ [0]"}, three => sub {Print "last $ _ [0]"}); $ array {$ foo} - & gt; ('talk');
Comments
Post a Comment