dejoha has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Calling OO-method From A Hash
by Anonymous Monk on Mar 03, 2004 at 02:50 UTC | |
by Fletch (Bishop) on Mar 03, 2004 at 02:58 UTC | |
by tinita (Parson) on Mar 03, 2004 at 09:56 UTC | |
| |
by Anonymous Monk on Mar 03, 2004 at 03:06 UTC | |
by Fletch (Bishop) on Mar 03, 2004 at 03:11 UTC | |
by Anonymous Monk on Mar 03, 2004 at 03:14 UTC | |
by dejoha (Novice) on Mar 03, 2004 at 05:12 UTC | |
by bart (Canon) on Mar 03, 2004 at 08:42 UTC | |
by dragonchild (Archbishop) on Mar 03, 2004 at 13:30 UTC | |
|
The debugger is your friend
by TomDLux (Vicar) on Mar 03, 2004 at 06:51 UTC |