Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Function name in a variable, can't recall the concept

by haukex (Chancellor)
on Apr 02, 2019 at 14:29 UTC ( #1232016=note: print w/replies, xml ) Need Help??


in reply to Function name in a variable, can't recall the concept

I'd say it's just code references, documented in perlref. See also Function object and "First-class functions" on Rosettacode, which have Perl and Python examples. %dispatch is a Dispatch table (and you probably meant to write the code references as foo => \&somefunc). I'm far from a Python expert, but AFAICT, these pieces of code should be pretty much equivalent:

#!/usr/bin/env perl use warnings; use strict; sub somefunc { print "Hello, $_[0]\n" } my %dispatch = ( foo => \&somefunc, bar => sub { print "World$_[0]\n" }, ); $dispatch{foo}->("Perl"); $dispatch{bar}->("!");
#!/usr/bin/env python3 def somefunc(x): print("Hello, "+x) dispatch = { 'foo': somefunc, 'bar': lambda x: print("World"+x), } dispatch["foo"]("Perl") dispatch["bar"]("!")

Note however that using a string as a reference is a symbolic reference and is generally discouraged (and generally not possible under strict): Why it's stupid to `use a variable as a variable name'. Usually it's better to use a hash instead, like the above %dispatch. Update: And your second example is probably better written as my $funcname = ( $someCondition ? \&foo : \&bar );

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1232016]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2020-03-31 10:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    To "Disagree to disagree" means to:









    Results (181 votes). Check out past polls.

    Notices?