我正在使用类似于以下的哈希表来存储可以在提示符下输入的字母以及该选项的描述和将被调用的函数。
my %main_menu = (
"l" => ["list locks", \&list_locks],
"n" => ["new lock", \&new_lock],
"u" => ["update lock", \&update_lock]
);
menu_prompt(\%main_menu)
产生以下菜单: ________________________
| l - list locks |
| n - new lock |
| u - update lock |
|________________________|
(l,n,u)>
当用户输入 'u' 时,会在提示符处调用 update_lock 函数。
现在,我想用一个新的哈希表 (
%lock_menu
) 生成一个类似的菜单。但是,我将首先提示用户输入他们希望更新的锁的 ID。Please enter the ID of a lock to update: 1 You are updating lock 1. __________________ | l - list users | | n - new user | |__________________| (p,u,c)>
I want to store the lock ID so that it is accessible to the lock menu functions. For example:
my %users_menu = ( "l" => ["list users", \&list_users], "n" => ["new user", \&new_user]);
I can't figure out how to "attach" the lock ID to the functions in the %users_menu
. So when 'l' is selected, list_users will be called with that number as its first argument.
I seem to remember that ML if you call a n-argument function in the ML language with only one argument it will produce a function that takes n-1 arguments. So for example, calling func(int,int,int) as func(5) would produce func(int,int) with the first argument saved as 5.
Is this possible in Perl? Or am I going about this the wrong way? Please let me know.
UPDATE: This is the function that prints a menu (print_options), prompts the user for a letter, and calls the corresponding function.
sub menu_prompt
{
my $options = shift;
print_options $options;
my $choice = <>;
chomp $choice;
if (defined $$options{$choice})
{
$$options{$choice}[1](); # no arguments
}
}
我想找到一种方法将此函数用于所有菜单,而不是编写一个单独的函数,将值传递给函数。
最佳答案
如果不发布更多示例代码,很难给出完整的答案,但是当您从哈希调用您的子时,为什么不将锁定值传递给它呢?
my $num = ... # get lock number;
$users_menu{"n"}[1]->($num)
# calls "new_user" passing it $num
问题编辑:
sub menu_prompt {
my $options = shift;
print_options $options;
my $choice = <>; # i assume the diamond operator got stripped
chomp $choice; # second my is in error
if (defined $$options{$choice}) {
return $$options{$choice}[1](@_);
# any additional arguments to menu_prompt will be passed to the sub
# return the value for future processing
}
}
关于perl - 在 Perl 中将值绑定(bind)到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1892026/