Taking some advice from the O'Reilly book, Perl Cookbook, recipe 19.12, I've worked up a CGI program that uses a %hash to pick from a variety of functions.
I'd like to call these as methods, instead of just functions, but I can't figure out how. Likely, this has a simple solution.
Relevent code:
sub prepare { my $class = shift; my $quiz = bless { }, $class; $quiz->init(@_); return $quiz; } sub begin { my $quiz = shift; # What should PopQuiz do? my $switchbox = { 'show' => \&Take_A_Quiz, 'list' => \&Quiz_List, 'score' => \&Score_Quiz, 'submit' => \&Submit_Quiz, }; # Pick Mode my $mode = $quiz->{params}{'__mode'} || 'list'; # Prepare the act to be performed my $act = $switchbox->{$mode}; # Perform &{$act}($quiz); }
Instead of calling &{ $act }( $quiz ), I would like to call the method, $quiz->$act( ); -- or something like this? Normally, I call methods in this fashion:
$quiz->method;In another subroutine, I am using a similar %hash to call other functions:
my %valid_question = ( 'boolean' => \&parse_boolean, 'multiple' => \&parse_multiple, 'identify' => \&parse_identify, 'essay' => \&parse_essay ); my $parse_type = $valid_question{ lc( $input ) };
Now, I want to call a method, but the only way I've figured out how to do it is this:
&{ $parse_type }( $quiz, @params );I wish I could do this OO style, and not have to pass the object literally:
$quiz->$parse_type( @params );I have a working example of the script online:
http://www.camandshayna.com/quiz/popquiz.cgiThanks,
~derek
In reply to Calling OO-method From A Hash by dejoha
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |