Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call a function which name is a variable?

I am trying to use this syntax to call a function "$name"(). I know this works for methods, but I do not if there is a way to do it with functions from a module.

I have tried this => sub b(){say "b";}; "b"();, but it does not work.

Any idea?

like image 740
Antonio Gamiz Delgado Avatar asked Jul 04 '19 09:07

Antonio Gamiz Delgado


People also ask

How do you call a function as a variable?

This also should allow you to pass in arguments: eval('var myfunc = ' + variable); myfunc(args, ...); If you don't need to pass in arguments this might be simpler. eval(variable + '();');

How do you call a function name?

Define a function named "myFunction", and make it display "Hello World!" in the <p> element. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.

Can we use a function name as a variable name?

The best suggestion is to discontinue the use of function names as variable names completely. However, in certain applications in which this is not possible, place the relevant code in a separate script and then invoke the script from the function.

How can I call a function given its name as a string?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.


1 Answers

@sena_kun has answerd me via Perl6 IRC channel, and it looks like the correct syntax would be: sub b(){say "best" }; ::('&b')();.

As you can see that looks like "magic", so instead of that, @sena_kun has told me this more comprehensible way: sub a {1.say}; sub b {2.say}; my @a = &a, &b; for @a -> &f { &f()}

like image 61
Antonio Gamiz Delgado Avatar answered Oct 31 '22 02:10

Antonio Gamiz Delgado