Hi, I'm having problems with getting a method in my object
to dispatch to other methods within the object.
Here's an example without an object, showing what I'm doing:
sub first {
print "This is first\n";
}
sub second {
print "This is second\n";
}
sub dispatch {
no strict 'refs';
my $command = shift;
print "In dispatch, command = $command\n";
my %dispatch = ( 'a'=>'first', 'b'=>'second' );
&{$dispatch{$command}}();
}
dispatch('a');
dispatch('b');
The output for this is:
In dispatch, command = a
This is first
In dispatch, command = b
This is second
Here I use the same concept with objectified code:
package FOO;
sub first {
print "This is first\n";
}
sub second {
print "This is second\n";
}
sub dispatch {
my $self = shift;
no strict 'refs';
my $command = shift;
print "In dispatch, command = $command\n";
my %dispatch = ( 'a'=>'first', 'b'=>'second' );
&{$self->{$dispatch{$command}}}();
}
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
return $self;
}
package ::;
my $foo = new FOO();
$foo->dispatch('a');
$foo->dispatch('b');
But now, it fails with the following error:
Undefined subroutine &main:: called at ./dispatch2.pl line 15.
My best guess is that perl is taking the curly braces after
the $self-> and interpreting that to mean that to mean
everything inside refers to a key in the blessed hash,
instead of evaluating everything and recognizing it as a
function call. Any suggestions on how to get around this?
-Dan
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.