in reply to Calling a method by name without eval()

atemerev

I'm away from a perl interpreter right now so this little snippet (from the the Perl Cookbook, recipe 11.4) will just have to do:

my %commands = ( "happy" => \&joy, "sad" => \&sullen, "done" => sub { die "See ya!" }, "mad" => \&angry, ); print "How are you? "; chomp($string = <STDIN>); if ($commands{$string}) { $commands{$string}->(); } else { print "No such command: $string\n"; }

The idea here is to store your function/method references in a hash (%commands). Then you call the method by looking it up in the hash, and passing in the params. I don't remember the exact context for this, but, most of the time when you're using eval'd strings or "soft references" you can use a hash to achieve the same results.

Good luck with it!

Kurt

Replies are listed 'Best First'.
Re^2: Calling a method by name without eval()
by chromatic (Archbishop) on Mar 23, 2008 at 21:13 UTC

    That's definitely a useful technique, but beware that these aren't methods: they don't go through method dispatch at all. You don't get polymorphism this way, unless you use a double-dispatch scheme.