9.5. Hashes of FunctionsWhen writing a complex application or network service in Perl, you might want to make a large number of commands available to your users. Such a program might have code like this to examine the user's selection and take appropriate action:
You can also store references to functions in your data structures, just
as you can store references to arrays or hashes:
In the second to last line, we check whether the specified command
name (in lowercase) exists in our "dispatch table",
%HoF. If so, we invoke the appropriate command by
dereferencing the hash value as a function and pass that function an
empty argument list. We could also have dereferenced it as
&{ $HoF{lc $cmd} }(), or, as of the 5.6 release
of Perl, simply $HoF{lc $cmd}().
![]() Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|