Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Suppose I have a hash whose values are anonymous functions,
e.g.,
Then, suppose I want to take input from the user and see if the things the user types are keys in the hash. If so, I execute the associated function.%functions = ( '?' => 0, 'HELLO' => sub { print "Hello, world.\n" }, 'HELP' => sub { print "Type 'hello' or 'goodbye'\n" }, 'GOODBYE' => sub { print "Goodbye...\n"; exit(0) } ); # have to initialize this outside declaration of %functions $functions{'?'} = $functions{'HELP'};
My question is this. At the spot to insert the code to execute the function, I would like to do this:while(<>) { $func = $_; chomp($func); $func = uc($func); if( defined($functions{$func}) ) { ### insert code here to execute function in hash ### } else { print "\"$func\" not defined\n"; } }
but perl won't let me. I have found that if I do this:&$functions{$func};
it works. Why doesn't the first work?my $code; $code = $functions{$func}; &$code;
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: using a hash of functions
by merlyn (Sage) on Sep 27, 2000 at 19:52 UTC | |
multiple keys - one value
by japhy (Canon) on Sep 27, 2000 at 21:44 UTC | |
by merlyn (Sage) on Sep 27, 2000 at 23:34 UTC | |
by japhy (Canon) on Sep 28, 2000 at 01:55 UTC | |
by bradcathey (Prior) on Dec 04, 2003 at 14:20 UTC | |
by merlyn (Sage) on Dec 04, 2003 at 21:17 UTC | |
by bradcathey (Prior) on Dec 05, 2003 at 02:14 UTC | |
| |
by jcwren (Prior) on Sep 27, 2000 at 21:56 UTC | |
by sandfly (Beadle) on Sep 11, 2003 at 22:14 UTC | |
by NetWallah (Canon) on Dec 04, 2003 at 06:39 UTC | |
by QM (Parson) on Dec 04, 2003 at 07:10 UTC | |
by NetWallah (Canon) on Dec 05, 2003 at 05:58 UTC | |
Re: using a hash of functions
by swiftone (Curate) on Sep 27, 2000 at 19:50 UTC | |
RE: using a hash of functions
by runrig (Abbot) on Sep 27, 2000 at 20:39 UTC |
Back to
Seekers of Perl Wisdom