I have a new question dealing with OO programming.

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.cgi

Thanks,

~derek


In reply to Calling OO-method From A Hash by dejoha

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.